Java語言程式設計(基礎篇)原書第十版 課後習題 第五章

一個好學生-葉紀杉發表於2015-10-21
import java.util.Scanner;
public class Code_Practice_5 {

    public static void main(String[] args) {

        // 5.1
        Scanner input = new Scanner(System.in);

        System.out.print("Enter an integer, the input ends if it is 0:");
        int number = input.nextInt();

        int countP = 0, countN = 0;
        int total = 0, count = 0;

        if (number != 0) {
            // 如果寫成while(true),會出現Unreachable code的問題,原因沒找到
            while (number != 0) {
                if (number > 0)
                    countP++;
                else
                    countN++;
                total += number;

                number = input.nextInt();
            }

            double average = total / (countP + countN);

            System.out.println("The number of positives is " + countP);
            System.out.println("The number of negatives is " + countN);
            System.out.println("The total is " + total);
            System.out.println("The average is " + average);
        }

        else
            System.out.println("No numbers are entered except 0");

    // 5.2
    final int NUMBER_OF_QUESTIONS = 5; // Number of questions
        int correctCount = 0 ; // Count the correct
        int count = 0; // Count the questions
        long startTime = System.currentTimeMillis();
        String output = " "; // output string is initially empty;
        Scanner input = new Scanner(System.in);

        while (count < NUMBER_OF_QUESTIONS) {
            // Generate two random single-digit integers
            int num1 = (int)(1 + Math.random() * 14);
            int num2 = (int)(1 + Math.random() * 14);

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

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

            count ++;

            output += "\n" + num1 + "+" + num2 + "=" + answer +
                ((num1 + num2 == answer) ? " correct" : " wrong");

        }

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

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

        // 5.3
        int kilo = 1;
        double pound = 0;
        System.out.println("千克" + "                       " + "    磅");
        for (int i = 0; i < 199; i++) {
            System.out.print(kilo);
            pound = kilo * 2.2;
            System.out.printf("%12.1f\n", pound);

            kilo++;
        }   

        // 5.4
        int miles = 1;
        double kilo = 0;
        System.out.println("英里" + "                       " + "    千米");
        for (int i = 0; i < 10; i++) {
            System.out.printf("%-9d",miles);
            kilo = miles * 1.609;
            System.out.printf("%-7.3f\n", kilo);
            miles++;
        }

        // 5.5
        int kilo1 = 1, pound2 = 20;
        double pound1 =  1, kilo2 = 1;
        System.out.println("千克" + "                       " + "    磅" +
                "                       "+"磅" + "                       " + "    千克");
        for (int i = 0; i < 199; i++) {
            System.out.print(kilo1);
            pound1 = kilo1 * 2.2;
            System.out.printf("%12.1f", pound1);
            for (int j = 0; j < 99; j++) {
                System.out.printf("%6d",pound2);
                kilo2 = pound2 / 2.2;
                System.out.printf("%8.2f\n",kilo2);
                pound2 += 5;
                break;
            }
            kilo1++;
        }

    // 5.6
    int miles1 = 1, kilo2 = 20;
        double kilo1 = 0, miles2 = 0;
        System.out.println("英里" + "                       " + "    千米" +
                "                       " + "千米" + "                       " + "    英里");
        for (int i = 0; i < 10; i++) {
            System.out.printf("%-9d",miles1);
            kilo1 = miles1 * 1.609;
            System.out.printf("%-7.3f", kilo1);
            for (int j = 0; j < 10; j++) {
                System.out.printf("%6d",kilo2);
                miles2 = kilo2 / 1.609;
                System.out.printf("%13.3f\n",miles2);
                kilo2 += 5;
                break;
            }
            miles1++;
        }

    // 5.7
    int tuition = 10000;
        int year = 0;
        int total = 0;

        while (year < 14) {
            tuition *= 1.05;
            year++;
            System.out.println(year + " " +tuition);
            while (year > 10) {
                total += tuition;
                break;
            }
        }

        System.out.println(total);
    // 5.8
    Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of student:");
        int num = input.nextInt();
        double highestScore = 0, higherScore = 0;
        String highestName = "", higherName = "";

        for (int count = 0; count < num; count++) {
            System.out.print("Enter the  " + (count + 1) + " student\'s name:");
            String name = input.next();
            System.out.print("Enter the  " + (count + 1) + " student\'s score:");
            double score = input.nextDouble();

            if (score > highestScore && score > higherScore) {
                highestScore = score;
                highestName = name;

            }
            else if (score < highestScore && score > higherScore){
                higherScore = score;
                higherName = name;
            }
        }

        System.out.println("The best student is " + highestName +
            " and the socre is " + highestScore);
        System.out.println("The second student is " + higherName +
                " and the socre is " + higherScore);

    // 5.9
    Scanner input = new Scanner(System.in);

            // Prompt the user to enter the number of students
            System.out.print("Enter the number of students: ");
            int numberOfStudents = input.nextInt();

            System.out.print("Enter a student name: ");
            String student1 = input.next();

            System.out.print("Enter a student score: ");
            double score1 = input.nextDouble();

            System.out.print("Enter a student name: ");
            String student2 = input.next();

            System.out.print("Enter a student score: ");
            double score2 = input.nextDouble();

            // Make sure that student1 is for the highest 
            // and student2 is for the second highest
            if (score1 < score2) {
              // Swap
              String tempString = student1;
              double tempScore = score1;

              student1 = student2;
              score1 = score2;

              student2 = tempString;
              score2 = tempScore;
            }

            for (int i = 0; i < numberOfStudents - 2; i++) {
              System.out.print("Enter a student name: ");
              String student = input.next();

              System.out.print("Enter a student score: ");
              double score = input.nextDouble();

              if (score > score1) {
                student2 = student1; // student1 now is the second highest
                score2 = score1;

                student1 = student; // new student becomes the highest
                score1 = score;
              }
              else if (score > score2) {
                student2 = student; // new student becomes the second highest
                score2 = score;
              }
            }

            System.out.println("Top two students:");
            System.out.println(student1 + "'s score is " + score1);
            System.out.println(student2 + "'s score is " + score2);


    // 5.10
    int count = 0;
        for (int i = 100; i < 1000; i++) {
            if (i % 5 == 0 && i % 6 == 0)
                System.out.print((++count % 10 != 0) ? i + " " : i + "\n");
        }

    // 5.11
    int count = 1;
        for (int i = 100; i < 1000; i++) {
            if (i % 5 == 0 ^ i % 6 == 0)
                System.out.print((count++ % 10 != 0) ? i + " " : i + "\n");
        }
    // 5.12
    int n = 1;
        while (Math.pow(n, 2) <= 12000)
            n++;
        System.out.println("This number is " + n);

    // 5.13
    int n = 1;
        while (n * n * n < 12000)
            n++;
        System.out.println("This number is " + (n-1));

    // 5.14
    Scanner input = new Scanner(System.in);

        System.out.print("Enter the first number:");
        int num1 = input.nextInt();

        System.out.print("Enter the second number:");
        int num2 = input.nextInt();

        int d = (num1 < num2) ? num1 : num2;
        for(; d >= 1; d--) {
            if ((num1 % d == 0) && (num2 % d == 0))
                break;
        }

        System.out.println("GCD of " + num1 + " and " + num2 +
            " is " + d);

    // 5.15
    int count = 1;
        for (int i = '!'; i < '~'; i++) 
            System.out.print((count++ % 10 != 0) ? (char)i + " "
                : (char)i + "\n");

    // 5.16
    Scanner input = new Scanner(System.in);

        System.out.print("Enter a integer:");
        int number = input.nextInt();
        int fac = 2; // initialize the factor
        System.out.println("The factors for " + number + " is ");

        while (fac <= number) {
            if (number % fac == 0) {
                number /= fac;
                System.out.print(fac + " ");
            }
            else
                fac++;
        }

    // 5.17
    Scanner input = new Scanner(System.in);

        // Prompt the user to enter the number of lines
        System.out.print("Enter the number of lines: ");
        int numberOfLines = input.nextInt();

        if (numberOfLines < 1 || numberOfLines > 15) {
              System.out.println("You must enter a number from 1 to 15");
              System.exit(0);
            }

            // Print lines
            for (int row = 1; row <= numberOfLines; row++) {

              for (int column = 1; column <= numberOfLines - row; column++)
                System.out.print("   ");


             for (int num = row; num >= 1; num--)
                System.out.print((num >= 10) ? " " + num : "  " + num);


             for (int num = 2; num <= row; num++)
                System.out.print((num >= 10) ? " " + num : "  " + num);

              // Start a new line
              System.out.println();
            }

    // 5.20
    int count = 1; // count the number of prime
        int num = 2; // number from 2 to 1000;
        boolean isPrime  = true; // the number is prime of not

        System.out.println("The number is from 2 to 1000.");

        while (num <= 1000){

            isPrime = true;

            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime)
                System.out.print((count++ % 8 != 0) ? num + " " : num + "\n");

            num++;
        }

    // 5.21
    Scanner input = new Scanner(System.in);

        // Promt enter the amount of loan
        System.out.print("Enter loan amount:");
        double loanAmount = input.nextDouble();

        // Promt enter the year of loan
        System.out.print("Enter loan year as a integer:");
        int yearOfLoan = input.nextInt();

        System.out.print("Interest Rate");
        System.out.print("\tMonthly Payment");
        System.out.println("\t\tTotal Payment"); // \t take 8 position

        for (double annualInterestRate = 5.0; annualInterestRate <= 8.0;
            annualInterestRate += 1.0 / 8) {
            // Obtain monthly interest rate
            double monthlyInterestRate = annualInterestRate / 1200;

            // Compute mortgage
            double monthlyPayment = loanAmount * monthlyInterestRate /
                (1 - (Math.pow(1 / (1 + monthlyInterestRate), yearOfLoan * 12)));
                double totalPayment = monthlyPayment * yearOfLoan * 12;

            // Display results
            System.out.printf("%5.3f%c %20.2f %20.2f\n", annualInterestRate, 
                '%', monthlyPayment, totalPayment);
        }   
    // 5.23
    final int N = 50000;
        double backwark = 0, forward = 0;
        double sum1 = 0,sum2 = 0;

        for (int i = 1; i <= N; i++)
            sum1 += 1.0 / i;

        for (int i = N; i >= 1; i--)
            sum2 += 1.0 / i;

        System.out.println("The result of forward computation is " + sum1);
        System.out.println("The result of backward computation is " + sum2);
        System.out.println("The diffrence between two result is " + (sum1 - sum2));

    // 5.24
    double sum = 0;
        for (int i = 1; i <= 97; i += 2) {
            sum += 1.0 * i / (i + 2);
        }
        System.out.println("The sum is " + sum);
    // 5.25

    for (int i = 10000; i <= 100000; i += 10000){
            double pi = 0;

            for (int j = 1; j <= i; j += 2) {
                pi += 1.0 / (2 * j - 1) - 1.0 / (2 * j + 1);
            }

            System.out.println("The pi is " + pi);
        }
    // 5.26
    double e = 1;
        double item = 1;

        for (int i = 1; i <= 100000; i++) {
          item = item / i;
          e += item;

          if (i == 10000 || i == 20000 || i == 30000 || i == 40000 ||
              i == 50000 || i == 60000 || i == 70000 || i == 80000 ||
              i == 90000 || i == 100000)
          System.out.println("The e is " + e + " for i = " + i);
        }
    // 5.27
    int count = 0;
        for (int i = 2001; i <= 2100; i++) {
            if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))
                System.out.print((++count % 10 == 0) ? i + "\n" : i + " ");




}

相關文章