JAVA语言程序设计基础篇(Chapter 5)课后习题参考答案

发布于:2022-12-26 ⋅ 阅读:(1558) ⋅ 点赞:(1)

1. (简答题)(Count positive and negative numbers and compute the average of numbers) 

Write  a program that reads an unspecified number of integers, determines how many  positive and negative values have been read, and computes the total and average of  the input values (not counting zeros). Your program ends with the input 0. Display  the average as a floating-point number. 

Here is a sample run:

import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter an  integer,the input ends if it is :");
        int positiveNum = 0, negativeNum = 0;
        double total = 0, average;
        int num = sc.nextInt();
        if (num != 0) {
            while (num != 0) {
                if (num > 0) {
                    positiveNum++;
                } else {
                    negativeNum++;
                }
                total = total + num;
                num = sc.nextInt();
            }
        } else {
            System.out.println("No numbers are entered except 0 ");
            System.exit(0);
        }
        average = total / (positiveNum + negativeNum);
        System.out.println("The number of positive is " + positiveNum);
        System.out.println("The number of negative is " + negativeNum);
        System.out.println("The totoal is " + total);
        System.out.println("The average is " + average);

    }

 

2. (简答题) (Find the highest score)

Write a program that prompts the user to enter the number of students and each student's name and score, and finally displays the name  of the student with the highest score.

import java.util.Scanner;

public class Demo2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the number of students: ");
        int number = sc.nextInt();
        String[] nameList = new String[number];
        int[] scoreList = new int[number];
        int highest = 0;
        for (int i = 0; i < number; i++) {
            System.out.println("Enter the name of the student: ");
            String name = sc.next();
            System.out.println("Enter the score of the student: ");
            int score = sc.nextInt();
            nameList[i] = name;
            scoreList[i] = score;
            if (i > 0 && scoreList[i] > scoreList[i - 1]) {
                highest = i;
            }
        }
        System.out.println("The student with the highest score is:" + nameList[highest]);
        System.out.println("The highest score is :" + scoreList[highest]);

    }
}

3. (简答题)(Compute the greatest common divisor) 

Another solution for Listing 5.9 to find  the greatest common divisor of two integers n1 and n2 is as follows: First find d to be the minimum of n1 and n2, then check whether d, d-1, d-2, . . . , 2, or 1 is  a divisor for both n1 and n2 in this order. The first such common divisor is the  greatest common divisor for n1 and n2. Write a program that prompts the user to  enter two positive integers and displays the gcd.

import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number: ");
        int n1 = sc.nextInt();
        System.out.println("Enter the second number: ");
        int n2 = sc.nextInt();
        int d = (n1 > n2) ? n2 : n1;
        while (d > 0) {
            if (n1 % d == 0 && n2 % d == 0) {
                System.out.println("The greatest divisor of two integers is " + d);
                break;
            }
            d--;
        }
    }
}

4. (简答题)(Find the factors of an integer) 

Write a program that reads an integer and displays  all its smallest factors in increasing order. For example, if the input integer is  120, the output should be as follows: 2, 2, 2, 3, 5.

import java.util.Scanner;

public class Demo4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String factors ="";
        System.out.println("Enter an integer: ");
        int num = sc.nextInt();
        for(int i=2;num != 1; ){
            if (num%i==0){
                num /= i;
                factors+=i+",";
            }
            else {
                i++;
            }
        }
        System.out.println("The factors are: "+factors);
    }
}

5. (简答题)(Display prime numbers between 2 and 1,000) 

Modify Listing 5.15 to display all  the prime numbers between 2 and 1,000, inclusive. Display eight prime numbers  per line. Numbers are separated by exactly one space.

public class Demo5 {
    public static void main(String[] args) {
        boolean flag;
        int line = 0;
        System.out.println("The prime numbers between 2 and 1000 is :");
        for (int i = 2; i <= 1000; i++) {
            flag = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                System.out.print(i + "\t");
                line++;
            }
            if (line != 0 && flag && line % 8 == 0 && line != 0) {
                System.out.println();
            }
        }
    }
}

6. (简答题)(Sum a series) Write a program to sum the following series:

   

public class Demo6 {
    public static void main(String[] args) {
        double n1 = 1.0;
        int n2 = 3;
        double sum = 0;
        for (; n1 <= 97; ) {
            sum += n1 / n2;
            n1 += 2;
            n2 += 2;
        }
        System.out.println(sum);
    }
}
}

 

7. (简答题)(Compute  ) 

You can approximate  by using the following series:

   

Write a program that displays the value for i=10000 , 20000, …, and  100000.

import java.util.Scanner;

public class Demo7 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pai(sc);
    }
    public static void pai(Scanner sc){
        System.out.println("Enter the value of i :");
        double sum = 0;
        int count = sc.nextInt();
        for (int i = 1; i <= count; ) {
            double a = Math.pow((-1.0), i + 1);
            double b = 2 * i - 1;
            double n = (a / b);
            sum = sum + n;
            i += 1;
        }
        double pai = 4 * sum;
        System.out.println("π = " + pai);
    }
}

 

8. (简答题)(Business: check ISBN-13) 

ISBN-13 is a new standard for indentifying books. It  uses 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit d13 is a checksum,  which is calculated from the other digits using the following formula:

   

If the checksum is 10, replace it with 0. Your program should read the input as a  string. Here are sample runs:

import java.util.Scanner;

public class Demo8 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        iSBN(sc);
    }
    public static void iSBN(Scanner sc){
        System.out.println("Enter the first 12 digits of an ISBN-13 as a string: ");
        String s = sc.next();
        int n = 0;
        if (s.length() != 12) {
            System.out.println(s + " is an invalid input ");
            System.exit(-1);
        }
        for (int i = 0; i < 12; i++) {
            if (i % 2 == 1) {
                n = n + 3 * Integer.parseInt(String.valueOf(s.charAt(i)));
            } else {
                n = n + Integer.parseInt(String.valueOf(s.charAt(i)));
            }
        }
        int d13 = 10 - n % 10;
        if(d13==10){
            s += "0";
        }else{
            s+= d13;
        }
        System.out.println("The ISBN-13 number is "+s);
    }
}

 

9. (简答题)(Occurrence of max numbers) 

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number  0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest  is 5 and the occurrence count for 5 is 4. 

(Hint: Maintain two variables, max and count. max stores the current max number, and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is  greater than max, assign it to max and reset count to 1. If the number is equal to  max, increment count by 1.)

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo9 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter numbers :");
        int num = sc.nextInt();
        List list = largest(num, sc);
        int largestNum = (int)list.get(0);
        int count =(int)list.get(1);
        System.out.println("The largest number is " + largestNum);
        System.out.println("The occurrence count  of the largest number is " + count);
    }

    public static List largest(int num, Scanner sc) {
        int largestNum = num;
        int count = 0;
        if (num != 0) {
            while (num != 0) {
                num = sc.nextInt();
                if (num > largestNum) {
                    largestNum = num;
                    count = 0;
                }
                if (num == largestNum) {
                    count++;
                }
            }
        }
        List list = new ArrayList<>();
        list.add(largestNum);
        list.add(count);
        return list;
    }
}

 

10. (简答题)(Reverse a string) 

Write a program that prompts the user to enter a string and  displays the string in reverse order.

import java.util.Scanner;

public class Demo10 {
    public static void main(String[] args) {
        System.out.println("Enter a string: ");
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        String str = reverse(s);
        System.out.println("The reversed string is " + str);
    }

    public static String reverse(String s) {
        String str = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            str = str + s.charAt(i);
        }
        return str;
    }
}

 


网站公告

今日签到

点亮在社区的每一天
去签到