欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java语言程序设计(基础篇)(原书第10版) 第五章编程练习题

程序员文章站 2022-04-02 23:03:03
...

心血来潮补一下之前没做完的课后题,争取全部做完,欢迎大家评论指正。

目录

Java语言程序设计(基础篇)(原书第10版) 第五章编程练习题

需要书籍或者相关资料可以私聊!!!

5-1 统计正数和负数的个教然后计算这些数的平均值

import java.util.Scanner;

public class Program5_1 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter an integer, the input ends if it is 0: ");
		
		int a = input.nextInt();
		
		int sum = 0,count1 = 0,count2 = 0;
		double average;
		
		while(a != 0) {
			sum += a;
			if(a > 0)
				count1++;
			else
				count2++;
			a = input.nextInt();
		}
		average = sum * 1.0 / (count1 + count2);
		System.out.println("The number of positives is " + count1);
		System.out.println("The number of negatives is " + count2);
		System.out.println("The total is " + sum);
		System.out.println("The average is " + average);

		input.close();
	}

}

5-2 重复加法

import java.util.Scanner;

public class Program5_2 {

   public static void main(String[] args) {
       final int NUMBER_OF_QUESTIONS = 10; // Number of questions
       int correctCount = 0; // Count the number of correct answers
       int count = 0; // Count the number of questions
       long startTime = System.currentTimeMillis();
       String output = ""; // output string is initially empty
       Scanner input = new Scanner(System.in);

       while (count < NUMBER_OF_QUESTIONS) {
           int number1 = (int)(Math.random() * 15) + 1;
           int number2 = (int)(Math.random() * 15) + 1;

           System.out.print(
                   "What is " + number1 + " + " + number2 + "? ");
           int answer = input.nextInt();

           if (number1 + number2 == answer) {
               System.out.println("You are correct!");
               correctCount++;
           }
           else
               System.out.println("Your answer is wrong.\n" + number1
                       + " + " + number2 + " should be " + (number1 + number2));

           // Increase the count
           count++;

           output += "\n" + number1 + "+" + number2 + "=" + answer +
                   ((number1 + number2 == answer) ? " correct" : " wrong");
       }

       long endTime = System.currentTimeMillis();
       long testTime = endTime - startTime;

       System.out.println("Correct count is " + correctCount +
               "\nTest time is " + testTime / 1000 + " seconds\n" + output);

       input.close();
   }

}

5-3 将千克转换成磅

public class Program5_3 {

    public static void main(String[] args) {
        System.out.printf("%-8s%5s\n", "千克", "磅");
        for (int i = 1; i <= 199; i += 2)
            System.out.printf("%-10d%5.1f\n", i, i*2.2);
    }

}

5-4 将英里转换成千米

public class Program5_4 {

	public static void main(String[] args) {
		System.out.printf("%-8s%5s\n", "英里", "千米");
		for (int i = 1; i <= 10; i++)
			System.out.printf("%-10d%7.3f\n", i, i*1.609);
	}

}

5-5 千克与磅之间的互换

public class Program5_5 {

    public static void main(String[] args) {
        System.out.printf("%-8s%5s         %-8s%5s\n", "千克", "磅", "磅", "千克");
        for (int i = 1, j = 20; i <= 199; i += 2, j += 5) {
            System.out.printf("%-10d%5.1f         ", i, i * 2.2);
            System.out.printf("%-10d%5.2f\n", j, j / 2.2);
        }
    }

}

5-6 英里与千米之间的互换

public class Program5_6 {

    public static void main(String[] args) {
        System.out.printf("%-8s%5s        %-8s%5s\n", "英里", "千米", "千米", "英里");
        for (int i = 1, j = 20; i <= 10; i++, j += 5) {
            System.out.printf("%-10d%7.3f       ", i, i * 1.609);
            System.out.printf("%-10d%7.3f\n", j, j / 1.609);
        }
    }

}

5-7 财务应用程序:计算将来的学费

public class Program5_7 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double m = 10000;
		for(int i = 1;i <= 10;i++)
			m *= 1.05;
		
		System.out.println("The tuition after 10 years is " + ((int)(m * 100) / 100.00));
		double sum = m;
		for(int i = 1;i <= 3;i++){
			m *= 1.05;
			sum += m;
		}
		System.out.println("The tuition for 4 years after 10 years is " + ((int)(sum * 100) / 100.00));
	}

}

5-8 找出最高分

import java.util.Scanner;

public class Program5_8 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of students: ");
        int n = input.nextInt();

        int maxScore = 0;
        String maxName = null;

        for (int i = 1; i <= n; i++) {
            System.out.print(i + " name and score: ");
            String name = input.next();
            int score = input.nextInt();
            if(maxScore < score){
                maxScore = score;
                maxName = name;
            }
        }
        System.out.println("The highest score is " + maxName + " : " + maxScore);

        input.close();
    }

}

5-9 找出两个分教最高的学生

import java.util.Scanner;

public class Program5_9 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		System.out.print("Enter the number of students: ");
		int n = input.nextInt();

		System.out.print("1 name and score: ");
		String Name1 = input.next();
		int score1 = input.nextInt();

		System.out.print("2 name and score: ");
		String Name2 = input.next();
		int score2 = input.nextInt();
		
		int max1Score,max2Score;
		String max1Name,max2Name;
		
		if(score1 >= score2) {
			max1Score = score1;
			max1Name = Name1;
			max2Score = score2;
			max2Name = Name2;
		}
		else {
			max1Score = score2;
			max1Name = Name2;
			max2Score = score1;
			max2Name = Name1;
		}
		for(int i = 3;i <= n;i++) {
			System.out.print(i + " name and score: ");
			Name1 = input.next();
			score1 = input.nextInt();
			if(score1 >= max1Score) {
				max2Score = max1Score;
				max2Name = max1Name;
				max1Score = score1;
				max1Name = Name1;
			}
			else if(score1 >= max2Score) {
				max2Score = score1;
				max2Name = Name1;
			}
		}
		System.out.println("The highest score is " + max1Name + " : " + max1Score);
		System.out.println("The second highest score is " + max2Name + " : " + max2Score);

		input.close();
	}

}

5-10 找出能被5和6整除的数

public class Program5_10 {

    public static void main(String[] args) {
        final int numberPerLine = 10;

        int cnt = 0;
        for (int i = 100; i <= 1000; i++) {
            if (i % 5 == 0 && i % 6 == 0) {
                cnt++;
                System.out.printf("%-6d", i);
                if(cnt % 10 == 0)
                    System.out.println();
            }
        }
    }

}

5-11 找出能被5或6整除,但不能被两者同时整除的数

public class Program5_11 {

    public static void main(String[] args) {
        final int NUMBER_PER_LINE = 10;

        int cnt = 0;
        for (int i = 100; i <= 200; i++) {
            if (i % 5 == 0 ^ i % 6 == 0) {
                cnt++;
                System.out.printf("%-6d", i);
                if(cnt % NUMBER_PER_LINE == 0)
                    System.out.println();
            }
        }
    }

}

5-12 求满足n2>12000的n的最小值

public class Program5_12 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 1;
		while(n*n <= 12000)
			n++;
		System.out.println(n);
	}

}

5-13 求满足n3<12000的n的最大值

public class Program5_13 {

    public static void main(String[] args) {
        int n = 1;
        while(n*n*n < 12000)
            n++;
        System.out.println(n-1);
    }

}

5-14 计算最大公约数

import java.util.Scanner;

public class Program5_14 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter two numbers : ");
        int n1 = input.nextInt();
        int n2 = input.nextInt();

        int d = Math.min(n1, n2);
        while(n1 % d != 0 || n2 % d != 0)
            d--;

        System.out.printf("The gcd of %d and %d is %d", n1, n2, d);

        input.close();
    }

}

5-15 显示ACSII码字符表

public class Program5_15 {

    public static void main(String[] args) {
        final int NUMBER_PER_LINE = 10;

        int cnt = 0;
        for(char i = '!'; i <= '~'; i++){
            System.out.print(i + " ");
            cnt++;
            if(cnt % NUMBER_PER_LINE == 0)
                System.out.println();
        }
    }

}

5-16 找出一个整数的因子

import java.util.Scanner;

public class Program5_16 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		System.out.print("Enter a number: ");
		int n = input.nextInt();

		System.out.print("Factors of " + n + " is : ");
		for(int i = 2;n != 1;i++) {
			while(n % i == 0) {
				n /= i;
				System.out.print(i + " ");
			}
		}
		System.out.println();

		input.close();
	}

}

5-17 显示金字塔

import java.util.Scanner;

public class Program5_17 {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter the number of lines: ");
		int n = input.nextInt();
		
		for(int i = 1;i <= n;i++) {
			for(int j = 1;j <= 2*(n-i);j++)
				System.out.print(" ");
			for(int m = i;m >= 1;m--)
				System.out.print(m + " ");
			for(int k = 2;k <= i;k++)
				System.out.print(k + " ");
			System.out.println();
		}

		input.close();
	}

}

5-18 使用循环语句打印4个图案

import java.util.Scanner;

public class Program5_18 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of lines: ");
        int n = input.nextInt();

        System.out.println("Pattern 1:");
        for(int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++)
                System.out.print(j + " ");
            System.out.println();
        }
        System.out.println();
        System.out.println("Pattern 2:");
        for(int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i + 1; j++)
                System.out.print(j + " ");
            System.out.println();
        }
        System.out.println();
        System.out.println("Pattern 3:");
        for(int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i; j++)
                System.out.print("  ");
            for (int j = i; j >= 1; j--)
                System.out.print(j + " ");
            System.out.println();
        }
        System.out.println();
        System.out.println("Pattern 4:");
        for(int i = 1; i <= n; i++) {
            for (int j = 1; j < i; j++)
                System.out.print("  ");
            for (int j = 1; j <= n - i + 1; j++)
                System.out.print(j + " ");
            System.out.println();
        }

        input.close();
    }

}

5-19 打印金字塔形的数字

public class Program5_19 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 8;
		
		for(int i = 1;i <= n;i++) {
			for(int j = 1;j <= 2*(n-i);j++)
				System.out.print("  ");
			int r = (int) Math.pow(2.0,i-1);
			for(int m = 1;m <= i;m++)
				System.out.printf("%4d", 1 << (m-1));
			for(int k = i-1;k >= 1;k--)
				System.out.printf("%4d", 1 << (k-1));
			System.out.println();
		}
	}

}

5-20 打印2到1000之间的素数

public class Program5_20 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	    final int NUMBER_OF_PRIMES_PER_LINE = 8; // Display 10 per line
	    int count = 0; // Count the number of prime numbers
	    int max = 1000;

	    // Repeatedly find prime numbers
	    for(int i = 2;i <= max;i++){
	      // Assume the number is prime
	    	boolean isPrime = true; // Is the current number prime?

	      // Test if number is prime
	    	for (int j = 2; j < i / 2; j++) {
	    		if (i % j == 0) { // If true, number is not prime
	    			isPrime = false; // Set isPrime to false          
	    			break; // Exit the for loop
	    		}
	    	}
	      // Print the prime number and increase the count
	      	if(isPrime == true) {
	    	  	count++; // Increase the count

	    	  	if (count % NUMBER_OF_PRIMES_PER_LINE == 0)
	          // Print the number and advance to the new line
	    	  		System.out.println(i);
	        	else
	        		System.out.print(i + " ");
	      	}
	    }
	}

}

5-21 财务应用程序:比较不同利率下的贷款

import java.util.Scanner;

public class Program5_21 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Loan Amount: ");
        double loanAmount = input.nextDouble();

        System.out.print("Number of years: ");
        int years = input.nextInt();

        System.out.printf("%-20s%-20s%s\n", "Interest Rate", "Monthly Payment", "Total Payment");
        for (double i = 5.0; i <= 8.0; i += 1.0/8) {
            double monthlyRate = i / 1200.0;
            double monthlyPayment = loanAmount * monthlyRate / (1 - 1 / Math.pow(1+monthlyRate, years * 12));
            System.out.printf("%.3f%%              %-20.2f%.2f\n", i, monthlyPayment, monthlyPayment * 12 * years);
        }

        input.close();
    }

}

5-22 财务应用程序:显示分期还贷时间表

import java.util.Scanner;

public class Program5_22 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		//用户输入贷款总额
		System.out.print("Loan Amount: ");
		Double loanAmount = input.nextDouble();
		
		//用户输入贷款年数
		System.out.print("Number of Years: ");
		int years = input.nextInt();
		
		//用户输入年利率
		System.out.print("Annual Interest Rate: ");
		double rate = input.nextDouble();
		double monthRate = rate / 1200;
		
		//计算每月还款数额和总还款数额
		double monthPay = loanAmount * monthRate / (1 - 1 / Math.pow(1 + monthRate, years * 12));
		System.out.printf("\n\nMonthly Payment: %.2f\n", monthPay);
		double totalPay = monthPay * 12 * years;
		System.out.printf("Total Payment: %.2f\n\n", totalPay);
		
		System.out.println("Payment#        Interest        Principal       Balance");
		
		double total = loanAmount;
		for(int i = 1;i <= 12 * years;i++) {
			double interest = monthRate * total;
			double principal = monthPay - interest;
			double balance = total - principal;

			System.out.printf("%d\t\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n", i, interest, principal, balance);
			
			total = balance;
		}

		input.close();
	}

}

5-23 示例抵消错误

public class Program5_23 {

    public static void main(String[] args) {
        final int NUMBER = 50000;

        System.out.print("From left to right is: ");
        double ans1 = 0;
        for (int i = 1; i <= NUMBER; i++)
            ans1 += 1.0 / i;
        System.out.println(ans1);

        System.out.print("From right to left is: ");
        double ans2 = 0;
        for (int i = NUMBER; i >= 1; i--)
            ans2 += 1.0 / i;
        System.out.println(ans2);
    }

}

5-24 数列求和

public class Program5_24 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final int MAX_NUMBER = 97;
		double sum = 0;
		
		for(int i = 1;i <= MAX_NUMBER;i += 2)
			sum += i * 1.0 / (i + 2);
		System.out.println("sum is : " + sum);
	}

}

5-25 计算π

public class Program5_25 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//使用数学公式估算pi的值
		
		double pi = 0,sum = 0;
		int flag = 1;
		for(int n = 10000;n <= 100000;n += 10000) {
			System.out.print("n = " + n + " : ");
			sum = 0;
			for(int i = 1;i <= n;i += 2) {
				sum += flag * 1.0 / i;
				flag *= -1;
			}
		
			pi = 4 * sum;
			System.out.println("pi = " + pi);
		}
	}

}

5-26 计算e

public class Program5_26 {

    public static void main(String[] args) {

        double e = 1, item = 1;
        int flag = 1;
        for(int n = 10000;n <= 100000;n += 10000) {
            System.out.print("n = " + n + " : ");

            for(int i = n-10000+1; i <= n; i++) {
                item /= i;
                e += item;
            }
            System.out.println("e = " + e);
        }
    }

}

5-27 显示闰年

public class Program5_27 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int year1 = 101;
		int year2 = 2100;
		final int NUMBER_OF_YEARS_PER_LINE = 10;
		int count = 0,num = 0;
		
		for(int i = year1;i <= year2;i++) {
			if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
				count++;
				num++;
				System.out.print(i + " ");
				if(count % NUMBER_OF_YEARS_PER_LINE == 0)
					System.out.println();

			}
		}
		System.out.println("\nThe number of leapyears from " + year1 + " to " + year2 
				+ " is " + num);
	}

}

5-28 显示每月第一天是星期几

import java.util.Scanner;

public class Program5_28 {

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter the year: ");
       int year = input.nextInt();

       System.out.print("Enter the first day of " + year + " as the day of the week (0-6): ");
       int day = input.nextInt();

       for (int i = 1; i <= 12; i++) {
           switch (i){
               case 1:
                   System.out.print("January 1, " + year + " is ");
                   break;
               case 2:
                   day = (day + 31) % 7;
                   System.out.print("February 1, " + year + " is ");
                   break;
               case 3:
                   day = (day + ((year%400 == 0 || (year%100 != 0 && year%4 == 0)) ? 29 : 28)) % 7;
                   System.out.print("March 1, " + year + " is ");
                   break;
               case 4:
                   day = (day + 31) % 7;
                   System.out.print("April 1, " + year + " is ");
                   break;
               case 5:
                   day = (day + 30) % 7;
                   System.out.print("May 1, " + year + " is ");
                   break;
               case 6:
                   day = (day + 31) % 7;
                   System.out.print("June 1, " + year + " is ");
                   break;
               case 7:
                   day = (day + 30) % 7;
                   System.out.print("July 1, " + year + " is ");
                   break;
               case 8:
                   day = (day + 31) % 7;
                   System.out.print("August 1, " + year + " is ");
                   break;
               case 9:
                   day = (day + 31) % 7;
                   System.out.print("September 1, " + year + " is ");
                   break;
               case 10:
                   day = (day + 30) % 7;
                   System.out.print("October 1, " + year + " is ");
                   break;
               case 11:
                   day = (day + 31) % 7;
                   System.out.print("November 1, " + year + " is ");
                   break;
               case 12:
                   day = (day + 30) % 7;
                   System.out.print("December 1, " + year + " is ");
                   break;
           }
           switch (day){
               case 0:
                   System.out.println("Sunday");
                   break;
               case 1:
                   System.out.println("Monday");
                   break;
               case 2:
                   System.out.println("Tuesday");
                   break;
               case 3:
                   System.out.println("Wednesday");
                   break;
               case 4:
                   System.out.println("Thursday");
                   break;
               case 5:
                   System.out.println("Friday");
                   break;
               case 6:
                   System.out.println("Saturday");
                   break;
           }
       }

       input.close();
   }

}

5-29 显示日历

import java.util.Scanner;

public class Program5_29 {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		int countDayPerLine = 7;

		System.out.print("Enter the year: ");
		int year = input.nextInt();
		System.out.print("Enter the first day of \" + year + \" as the day of the week (0-6): ");
		int firstDay = input.nextInt();

		int count;
		for(int i = 1;i <= 12;i++) {
			int day = 1;
			int dayCount = 0;
			System.out.print("\t\t  ");
			switch (i){
				case 1:
					dayCount = 31;
					System.out.print("January ");
					break;
				case 2:
					dayCount = (year%400 == 0 || (year%100 != 0 && year%4 == 0)) ? 29 : 28;
					System.out.print("February ");
					break;
				case 3:
					dayCount = 31;
					System.out.print("March ");
					break;
				case 4:
					dayCount = 30;
					System.out.print("April ");
					break;
				case 5:
					dayCount = 31;
					System.out.print("May ");
					break;
				case 6:
					dayCount = 30;
					System.out.print("June ");
					break;
				case 7:
					dayCount = 31;
					System.out.print("July ");
					break;
				case 8:
					dayCount = 31;
					System.out.print("August ");
					break;
				case 9:
					dayCount = 30;
					System.out.print("September ");
					break;
				case 10:
					dayCount = 31;
					System.out.print("October ");
					break;
				case 11:
					dayCount = 30;
					System.out.print("November ");
					break;
				case 12:
					dayCount = 31;
					System.out.print("December ");
					break;
			}
			System.out.println(year);
			System.out.println("------------------------------------------------");
			System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat");
			for(count = 1; count <= 5*7; count++) {
				if(count <= firstDay) System.out.print("\t");
				else {
					System.out.printf("%-4d", day);
					day++;
				}
				if(day > dayCount)
					break;
				if(count % countDayPerLine == 0)
					System.out.println();
			}
			System.out.println();
			System.out.println();
			firstDay = count % 7;
		}

		input.close();
	}

}

5-30 财务应用程序:复利值

import java.util.Scanner;

public class Program5_30 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		System.out.print("Please enter the monthly deposit amount: ");
		double depositMonthly = input.nextDouble();
		System.out.print("Please enter the annual interest rate: ");
		double annualRate = input.nextDouble();
		double monthlyRate = annualRate / 1200;
		System.out.print("Please enter the number of month: ");
		int monthNum = input.nextInt();

		double deposit = 0;

		for(int i = 1; i <= monthNum; i++) {
			deposit += depositMonthly;
			deposit *= 1 + monthlyRate;
		}
		System.out.printf("After %d months, the amount is %.3f\n", monthNum, deposit);

		input.close();
	}

}

5-31 财务应用程序:计算CD价值

import java.util.Scanner;

public class Program5_31 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the initial deposit amount: ");
        double amount = input.nextDouble();

        System.out.print("Enter annual percentage yield: ");
        double monthlyRate = input.nextDouble() / 1200;

        System.out.print("Enter maturity period (number of months): ");
        int num = input.nextInt();

        System.out.println("Month   CD Value");
        for (int i = 1; i <= num; i++) {
            amount += amount * monthlyRate;
            System.out.printf("%-8d%.2f\n", i, amount);
        }

        input.close();
    }

}

5-32 游戏:**

import java.util.Scanner;

public class Program5_32 {

    public static void main(String[] args) {
        // Generate a lottery
        int num1 = (int)(Math.random() * 10);
        int num2 = (int)(Math.random() * 10);
        while(num1 == num2)
            num2 = (int)(Math.random() * 10);
        int lottery = num1 * 10 + num2;

        // Prompt the user to enter a guess
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your lottery pick (two digits): ");
        int guess = input.nextInt();

        // Get digits from lottery
        int lotteryDigit1 = lottery / 10;
        int lotteryDigit2 = lottery % 10;

        // Get digits from guess
        int guessDigit1 = guess / 10;
        int guessDigit2 = guess % 10;

        System.out.println("The lottery number is " + lottery);

        // Check the guess
        if (guess == lottery)
            System.out.println("Exact match: you win $10,000");
        else if (guessDigit2 == lotteryDigit1
                && guessDigit1 == lotteryDigit2)
            System.out.println("Match all digits: you win $3,000");
        else if (guessDigit1 == lotteryDigit1
                || guessDigit1 == lotteryDigit2
                || guessDigit2 == lotteryDigit1
                || guessDigit2 == lotteryDigit2)
            System.out.println("Match one digit: you win $1,000");
        else
            System.out.println("Sorry, no match");

        input.close();
    }

}

5-33 完全数

public class Program5_33 {

	public static void main(String[] args) {
		System.out.println("Complete number below 10000: ");

		for(int n = 2; n <= 10000; n++) {
			int sum = 0;
			for(int j = 1; j <= n/2; j++)
				if(n % j == 0) sum += j;
			if(sum == n)
				System.out.println(n);
		}
	}

}

5-34 游戏:石头、剪刀、布

import java.util.Scanner;

public class Program5_34 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner input = new Scanner(System.in);
		
		int computerWin = 0;
		int playerWin = 0;
		while(true) {
			int n = (int)(Math.random()*3);
			
			System.out.print("scissor (0), rock (1),paper (2):");
			int m = input.nextInt();
			System.out.print("The computer is ");
			if(n == 0)
			{
				System.out.print("scissor. ");
				if(m == 0) System.out.println("You are scissor too. It is a draw");
				if(m == 1) {
					System.out.println("You are rock. You won");
					playerWin++;
				}
				if(m == 2) {
					System.out.println("You are paper. You lost");
					computerWin++;
				}
			}
			if(n == 1)
			{
				System.out.print("rock. ");
				if(m == 0) {
					System.out.println("You are scissor. You lost");
					computerWin++;
				}
				if(m == 1) System.out.println("You are rock too. It is a draw");
				if(m == 2) {
					System.out.println("You are paper. You won");
					playerWin++;
				}
			}
			if(n == 2)
			{
				System.out.print("paper. ");
				if(m == 0) {
					System.out.println("You are scissor. You won");
					playerWin++;
				}
				if(m == 1) {
					System.out.println("You are rock. You lost");
					computerWin++;
				}
				if(m == 2) System.out.println("You are paper too. It is a draw");
			}
			if(computerWin == 2) {
				System.out.println("Game Over! You lost");
				break;
			}
			if(playerWin == 2) {
				System.out.println("Game Over! You win");
				break;
			}
		}

		input.close();
	}

}

5-35 加法

public class Program5_35 {

    public static void main(String[] args) {
        double sum = 0.0;

        for (int i = 1; i <= 624; i++)
            sum += 1 / (Math.pow(i, 0.5) + Math.pow(i + 1, 0.5));
        System.out.println("sum is " + sum);
    }

}

5-36 商业应用程序:检测ISBN

import java.util.Scanner;

public class Program5_36 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the first 9 digits of an ISBN as integer: ");
        String s = input.next();

        int sum = 0;
        for (int i = 0; i < 9; i++)
            sum += (s.charAt(i) - '0') * (i+1);

        int d10 = sum % 11;
        if(d10 == 10)
            System.out.println("The ISBN-10 number is " + s + 'X');
        else
            System.out.println("The ISBN-10 number is " + s + d10);

        input.close();
    }

}

5-37 十进制到二进制

import java.util.Scanner;

public class Program5_37 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");

        int num = input.nextInt();
        int m = num;
        String s = "";

        while(m > 0){
            s = (m % 2) + s;
            m /= 2;
        }

        System.out.println(num + "'s binary is " + s);

        input.close();
    }

}

5-38 十进制到八进制

import java.util.Scanner;

public class Program5_38 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");

        int num = input.nextInt();
        int m = num;
        String s = "";

        while(m > 0){
            s = (m % 8) + s;
            m /= 8;
        }

        System.out.println(num + "'s octal is " + s);

        input.close();
    }

}

5-39 财务应用程序:求出销售总额

public class Program5_39 {

    public static void main(String[] args) {
        final int BASIC_SALARY = 5000;

        int sales = 10000;
        double mySalary = BASIC_SALARY + 5000*0.08 + 5000*0.1 + (sales - 10000) * 0.12;
        while(mySalary < 30000){
            sales++;
            mySalary = BASIC_SALARY + 5000*0.08 + 5000*0.1 + (sales - 10000) * 0.12;
        }
        System.out.println("The minimum sales you have to complete is " + sales);
    }

}

5-40 模拟:正面或反面

public class Program5_40 {

    public static void main(String[] args) {
        final int TIMES = 1000000;

        int cnt1 = 0;
        int cnt2 = 0;
        for (int i = 0; i < TIMES; i++) {
            int n = (int)(Math.random() * 2);
            if(n == 1)
                cnt1++;
            else
                cnt2++;
        }
        System.out.printf("The coin appears %d times on the front\n", cnt1);
        System.out.printf("The coin appears %d times on the back\n", cnt2);
    }

}

5-41 最大数的出现次数

import java.util.Scanner;

public class Program5_41 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter numbers: ");
        int max = 0, count = 0;
        int num = input.nextInt();
        while(num != 0){
            if(num > max){
                max = num;
                count = 1;
            }else if(num == max)
                count++;
            num = input.nextInt();
        }

        System.out.println("The largest number is " + max);
        System.out.println("The occurrence count of the largest number is " + count);

        input.close();
    }

}

5-42 财务应用程序:求出销售额

import java.util.Scanner;

public class Program5_42 {

    public static void main(String[] args) {
        final int BASIC_SALARY = 5000;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter the commission sought: ");
        int commissionSought = input.nextInt();

        int sales = 10000;
        double mySalary = BASIC_SALARY + 5000*0.08 + 5000*0.1 + (sales - 10000) * 0.12;

        for (;mySalary <= commissionSought; sales++)
            mySalary = BASIC_SALARY + 5000*0.08 + 5000*0.1 + (sales - 10000) * 0.12;

        System.out.println("The minimum sales you have to complete is " + (sales-1));

        input.close();
    }

}

5-43 数学方面:组合

public class Program5_43 {

    public static void main(String[] args) {
        final int MAX_NUMBER = 7;

        int count = 0;

        for (int i = 1; i <= 7; i++)
            for(int j = i+1; j <= 7; j++) {
                System.out.println(i + " " + j);
                count++;
            }

        System.out.println("The total number of all combinations is " + count);
    }

}

5-44 计算机体系结构:比特级的操作

import java.util.Scanner;

public class Program5_44 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        int num = input.nextInt();

        String bits = "";

        for (int i = 15; i >= 0; i--)
            bits += (num >> i) & 1;

        System.out.println("The bits are " + bits);

        input.close();
    }

}

5-45 统计:计算平均值和标准方差

import java.util.Scanner;

public class Program5_45 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        double sum = 0.0, squareSum = 0.0;

        System.out.print("Enter ten numbers: ");
        for (int i = 0; i < 10; i++) {
            double num = input.nextDouble();
            sum += num;
            squareSum += num * num;
        }

        double mean = sum / 10;
        double deviation = Math.sqrt((squareSum - sum * sum / 10) / 9);

        System.out.printf("The mean is %.2f\n", mean);
        System.out.printf("The standard deviation is %.5f\n", deviation);

        input.close();
    }

}

5-46 倒排一个字符串

import java.util.Scanner;

public class Program5_46 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = input.nextLine();

        System.out.print("The reversed string is ");
        for (int i = str.length()-1; i >= 0; i--)
            System.out.print(str.charAt(i));
        System.out.println();

        input.close();
    }

}

5-47 商业:检测ISBN-13

import java.util.Scanner;

public class Program5_47 {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		System.out.print("Enter the first 12 digits of an ISBN-13 as a string: ");
		String isbn = input.next();
		
		int sum = 0,d13 = 0;

		if(isbn.length() == 12) {
			for(int i = 0; i < 12; i++) {
				if(i % 2 == 0)
					sum += (int) isbn.charAt(i) - '0';
				else
					sum += 3 * ((int) isbn.charAt(i) - '0');
			}
			d13 = (10 - sum % 10) % 10;
			isbn += d13;
			System.out.println("The ISBN-13 number is " + isbn);
		}
		else
			System.out.println(isbn + " is an invalid input");

		input.close();
	}

}

5-48 处理字符串

import java.util.Scanner;

public class Program5_48 {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		System.out.print("Enter a string: ");
		String str1 = input.nextLine();
		String str2 = "";
		
		for(int i = 0;i < str1.length(); i++)
			if(i % 2 == 0)
				str2 += str1.charAt(i);
		
		System.out.println(str2);

		input.close();
	}

}

5-49 对元音和辅音进行计数

import java.util.Scanner;

public class Program5_49 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = input.nextLine();

        int vowel = 0, consonant = 0;
        for (int i = 0; i < str.length(); i++)
            if(Character.isLetter(str.charAt(i))){
                char c = Character.toLowerCase(str.charAt(i));
                if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                    vowel++;
                else
                    consonant++;
            }

        System.out.println("The number of vowels is " + vowel);
        System.out.println("The number of consonants is " + consonant);

        input.close();
    }

}

5-50 对大写字母计数

import java.util.Scanner;

public class Program5_50 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = input.nextLine();

        int uppercase = 0;
        for (int i = 0; i < str.length(); i++)
            if(Character.isUpperCase(str.charAt(i)))
                uppercase++;

        System.out.println("The number of uppercase letters is " + uppercase);

        input.close();
    }

}

5-51 最长的共同前缀

import java.util.Scanner;

public class Program5_51 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the first string: ");
        String str1 = input.nextLine();

        System.out.print("Enter the second string: ");
        String str2 = input.nextLine();

        if(str1.length() <= str2.length()){
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
        String ans = "";
        for (int i = 0; i < str2.length(); i++) {
            boolean flag = true;
            for (int j = 0; j <= i; j++)
                if(str1.charAt(j) != str2.charAt(j)){
                    flag = false;
                    break;
                }
            if(flag)
                ans = str2.substring(0, i+1);
        }

        if(ans.length() > 0)
            System.out.println("The common prefix is " + ans);
        else
            System.out.println(str1 + " and " + str2 + " have no common prefix");

        input.close();
    }

}
相关标签: java