第六章第二十四题(显示当前日期和时间)(Display current date and time) – 编程练习题答案

**6.24(显示当前日期和时间)程序清单2-7显示当前时间。改进这个例子,显示当前的日期和时间。程序清单6-12中日历例子可以提供一些如何求年、月和日的思路。

**6.24(Display current date and time) Listing 2.7, ShowCurrentTime.java, displays the current time. Revise this example to display the current date and time. The calendar example in Listing 6.12, PrintCalendar.java, should give you some ideas on how to find the year, month, and day.

下面是参考答案代码:

public class Ans6_24_page202 {
    /** Main method */
    public static void main(String[] args) {
        // Obtain the total milliseconds since midnight, Jan 1, 1970
        long totalMilliseconds = System.currentTimeMillis();

        // Obtain the total seconds since midnight, Jan 1, 1970
        long totalSeconds = totalMilliseconds / 1000;

        // Compute the current second in the minute in the hour
        long currentSecond = totalSeconds % 60;

        // Obtain the total minutes
        long totalMinutes = totalSeconds / 60;

        // Compute the current minute in the hour
        long currentMinute = totalMinutes % 60;

        // Obtain the total hours
        long totalHours = totalMinutes / 60;

        // Compute the current hour
        long currentHour = totalHours % 24;

        long totalDays = totalHours / 24;

        int currentYear = 1970;

        while (totalDays >= 365) {
            if (isLeapYear(currentYear))
                totalDays -= 366;
            else
                totalDays -= 365;
            currentYear++;
        }

        int currentMonths = 1;
        while (totalDays >= 28) {
            if (currentMonths == 1 || currentMonths == 3 || currentMonths == 5 || currentMonths == 7
                    || currentMonths == 8 || currentMonths == 10 || currentMonths == 12) {
                totalDays -= 31;
                currentMonths++;
            } else if (currentMonths == 4 || currentMonths == 6 || currentMonths == 9 || currentMonths == 11) {
                totalDays -= 30;
                currentMonths++;
            } else if (isLeapYear(currentYear) && currentMonths == 2) {
                totalDays -= 29;
                currentMonths++;
            } else {
                totalDays -= 28;
                currentMonths++;
            }
        }

        long currentDay;
        if (totalDays == 0)
            currentDay = 1;
        else
            currentDay = totalDays + 1;

        // GMT+8
        if (currentHour+8 >= 24) {
            currentHour = currentHour+8-24;
        }

        // Display results
        System.out.println("Current data is " + currentYear +
                "-"+currentMonths+"-"+currentDay+ "\nCurrent time is " +
                currentHour+":"+currentMinute+":"+currentSecond+" (GMT+8)");
    }

    /** Determine if it is a leap year */
    public static boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十三题(指定字符的出现次数)(Occurrences of a specified character) – 编程练习题答案

*6.23(指定字符的出现次数)使用下面的方法头编写一个方法,找到一个字符串中指定字符的出现次数。

public static int count(String str, char a)

例如,count(“Welcome”,‘e’)返回2。编写一个测试程序,提示用户输入一个字符串以及一个字符,显示该字符在字符串中出现的次数。

*6.23(Occurrences of a specified character)Write a method that finds the number of occurrences of a specified character in a string using the following header:

public static int count(String str, char a)

For example, count(“Welcome”, ‘e’) returns 2. Write a test program that prompts the user to enter a string followed by a character then displays the number of occurrences of the character in the string.

下面是参考答案代码:

import java.util.Scanner;

public class Ans6_23_page202 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string and a character: ");
        String aStr = input.next();
        char aChar = input.next().charAt(0);
        System.out.println(count(aStr,aChar));
    }
    public static int count(String str, char a) {
        int count = 0;
        for (int i = 0; i < str.length(); i ++) {
            if (str.charAt(i) == a)
                count++;
        }
        return count;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十二题(数学:平方根的近似求法)(Math: approximate the square root) – 编程练习题答案

**6.22(数学:平方根的近似求法)有几种实现Math类中sqrt方法的技术。其中一个称为巴比伦法。它通过使用下面的公式反复计算近似地得到一个数字n的平方根:

nextGuess = (lastGuess + n / lastGuess) / 2

当nextGuess和lastGuess几乎相同时,nextGuess就是平方根的近似值。最初的猜测值可以是任意一个正值(例如1)。这个值就是lastGuess的初始值。如果nextGuess和lastGuess的差小于很小的数,比如0.0001,就可以认为nextGuess是n的平方根的近似值;否则,nextGuess就成为lastGuess,求近似值的过程继续执行。实现下面的方法,返回n的平方根。

public static double sqrt(long n)

**6.22(Math: approximate the square root) There are several techniques for implementing the sqrt method in the Math class. One such technique is known as the Babylonian method. It approximates the square root of a number, n, by repeatedly performing the calculation using the following formula:

nextGuess = (lastGuess + n / lastGuess) / 2

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root. The initial guess can be any positive value (e.g., 1). This value will be the starting value for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of n. If not, nextGuess becomes lastGuess and the approximation process continues. Implement the following method that returns the square root of n:

public static double sqrt(long n)

下面是参考答案代码:

public class Ans6_22_page202 {
    public static void main(String[] args) {
        System.out.println(sqrt(2));
    }
    public static double sqrt(long n) {
        double Guess;
        double nextGuess = 1;
        do {
            Guess = nextGuess;
            nextGuess = (Guess + n / Guess) / 2;
        } while (Guess - nextGuess >= 0.0001 || nextGuess - Guess >= 0.0001);
        return nextGuess;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十一题(电话按键盘)(Phone keypads) – 编程练习题答案

*6.21(电话按键盘)国际标准的字母/数字匹配图如编程练习题4.15所示,编写一个方法,返回给定大写字母的数字,如下所示:

int getNumber(char uppercaseLetter)

编写一个测试程序,提示用户输入字符串形式的电话号码。输入的数字可能会包含字母。程序将字母(大写或者小写)翻译成一个数字,然后保持其他字符不变。

*6.21(Phone keypads)The international standard letter/number mapping for telephones is given in Programming Exercise 4.15. Write a method that returns a number, given an uppercase letter, as follows:

int getNumber(char uppercaseLetter)

Write a test program that prompts the user to enter a phone number as a string. The input number may contain letters. The program translates a letter (uppercase or lowercase) to a digit and leaves all other characters intact.

下面是参考答案代码:

import java.util.Scanner;

public class Ans6_21_page201 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String phoneNumber = input.nextLine().toUpperCase();
        for (int i =0; i < phoneNumber.length(); i++) {
            if (Character.isDigit(phoneNumber.charAt(i))) {
                System.out.print(phoneNumber.charAt(i));
            }
            else if (getNumber(phoneNumber.charAt(i)) == 1)
                System.out.print("-");
            else
                System.out.print(getNumber(phoneNumber.charAt(i)));
        }
    }
    public static int getNumber(char uppercaseLetter) {
        int num = 99;
        switch (uppercaseLetter+"") {
            case "-":
                num = 1;
                break;
            case "A":
                num = 2;
                break;
            case "B":
                num = 2;
                break;
            case "C":
                num = 2;
                break;
            case "D":
                num = 3;
                break;
            case "E":
                num = 3;
                break;
            case "F":
                num = 3;
                break;
            case "G":
                num = 4;
                break;
            case "H":
                num = 4;
                break;
            case "I":
                num = 4;
                break;
            case "J":
                num = 5;
                break;
            case "K":
                num = 5;
                break;
            case "L":
                num = 5;
                break;
            case "M":
                num = 6;
                break;
            case "N":
                num = 6;
                break;
            case "O":
                num = 6;
                break;
            case "P":
                num = 7;
                break;
            case "Q":
                num = 7;
                break;
            case "R":
                num = 7;
                break;
            case "S":
                num = 7;
                break;
            case "T":
                num = 8;
                break;
            case "U":
                num = 8;
                break;
            case "V":
                num = 8;
                break;
            case "W":
                num = 9;
                break;
            case "X":
                num = 9;
                break;
            case "Y":
                num = 9;
                break;
            case "Z":
                num = 9;
        }
        return num;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十题(计算一个字符串中字母的个数)(Count the letters in a string) – 编程练习题答案

*6.20(计算一个字符串中字母的个数)编写一个方法,使用下面的方法头计算字符串中的字母个数:
public static int countLetters(String s)

编写一个测试程序,提示用户输入字符串,然后显示字符串中的字母个数。
*6.20(Count the letters in a string) Write a method that counts the number of letters in a string using the following header:
public static int countLetters(String s)

Write a test program that prompts the user to enter a string and displays the number of letters in the string.

下面是参考答案代码:

import java.util.Scanner;

public class Ans6_20_page201 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter : ");
        String s = input.nextLine();
        System.out.println("The number of letters is "+ countLetters(s));
    }
    public static int countLetters(String s) {
        int count = 0;
        for (int i = 0;i < s.length();i++) {
            if (Character.isLetter(s.charAt(i)))
                count++;
        }
        return count;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)