第六章第三十一题(金融应用:信用卡号的合法性验证)(Financial: credit card number validation) – 编程练习题答案

**6.31(金融应用:信用卡号的合法性验证)信用卡号遵循某种模式。一个信用卡号必须是13到16位的整数。它的开头必须是:

4,指Visa卡

5,指Master卡

37,指American Express 卡

6,指Discover卡

1954年,IBM的Hans Luhn提出一种算法,用于验证信用卡号的有效性。这个算法在确定输入的卡号是否正确,或者这张信用卡是否被扫描仪正确扫描方面是非常有用的。遵循这个合法性检测可以生成所有的信用卡号,通常称之为Luhn检测或者Mod 10检测,可以如下描述(为了方便解释,假设卡号4388576018402626):

1.从右到左对偶数位数字翻倍。如果对某个数字翻倍之后的结果是一个两位数,那么就将这两位加在一起得到一位数。

2.现在将第一步得到的所有一位数相加。

3.将卡号里从右到左奇数位上的所有数字相加。

4.将第二步和第三步得到的结果相加。

5.如果第四步得到的结果能被10整除,那么卡号是合法的;否则,卡号是不合法的。例如,号码4388576018402626是不合法的,但是号码4388576018410707是合法的。

编写程序,提示用户输入一个long型整数的信用卡号码,显示这个数字是合法的还是非法的。
使用下面的方法设计程序:
public static boolean isValid(long number)

public static int sumOfDoubleEvenPlace(long number)

public static int getDigit(int number)

public static int sumOfOddPlace(long number)

public static boolean prefixMatched(long number, int d)

public static int getSize(long d)

public static long getPrefix(long number, int k)

下面是程序的运行示例:(你也可以通过将输入作为一个字符串读入,以及对字符串进行处理来验证信用卡卡号。)

Enter a credit card number as a long integer: 4388576018410707
4388576018410707 is valid

Enter a credit card number as a long integer: 4388576018402626
4388576018402626 is invalid

**6.31(Financial: credit card number validation) Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits. It must start with

4 for Visa cards

5 for Master cards

37 for American Express cards

6 for Discover cards

In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly, or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388576018402626):
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.

Now add all single-digit numbers from Step 1.
Add all digits in the odd places from right to left in the card number.

Sum the results from Step 2 and Step 3.

If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.

Write a program that prompts the user to enter a credit card number as a long integer. Display whether the number is valid or invalid.
Design your program to use the following methods:

public static boolean isValid(long number)

public static int sumOfDoubleEvenPlace(long number)

public static int getDigit(int number)

public static int sumOfOddPlace(long number)

public static boolean prefixMatched(long number, int d)

public static int getSize(long d)

public static long getPrefix(long number, int k)

Here are sample runs of the program: (You may also implement this program by reading the input as a string and processing the string to validate the credit card.)

Enter a credit card number as a long integer: 4388576018410707
4388576018410707 is valid

Enter a credit card number as a long integer: 4388576018402626
4388576018402626 is invalid

下面是参考答案代码:

import java.util.Scanner;

public class Ans6_31_page203 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a credit card number as a long integer:");
        long number = input.nextLong();
        if (isVa1id(number) && divide(number))
            System.out.println(number + " is valid");
        else
            System.out.println(number + " is invalid");
        }

    // Step 0
    public static boolean isVa1id(long number) {
        if (prefixMatched(number,4) || prefixMatched(number,5) ||
                prefixMatched(number,37) || prefixMatched(number,6)) {
            return (number + "").length() >= 13 && (number + "").length() <= 16;
        }
        else
            return false;
    }

    // Get the result from Step 2
    public static int getEven(long number) {
        int getEven = 0;
        for (int i = 0; i < (number+"").length(); i+=2) {
            char n = (number + "").charAt(i);
            int num = Integer.parseInt(Character.toString(n));
            if (num * 2 > 9)
                num = (num * 2 / 10) + (num * 2 % 10);
            else if (num * 2 < 10)
                num = num * 2;
            getEven += num;
        }
        return getEven;
    }

    // Get the result from Step 3
    public static int getOdd(long number) {
        int getOdd = 0;
        for (int i = 1; i < (number+"").length(); i+=2) {
            char n = (number + "").charAt(i);
            int num = Integer.parseInt(Character.toString(n));
            getOdd += num;
        }
        return getOdd;
    }

    // Return sum
    public static int sumOfOddAndEven(long number) {
        return getEven(number) + getOdd(number);
    }

    // Return true if the digit d is a prefix for number
    public static boolean prefixMatched(long number, int d) {
        String strNumber = number + "";
        int charNumber0 = Integer.parseInt(strNumber.substring(0,(d+"").length()));
        return charNumber0 == d;
    }

    public static boolean divide(long d) {
        return sumOfOddAndEven(d) % 10 == 0;
    }
}

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

第六章第三十题(游戏:双骰子赌博)(Game: craps) – 编程练习题答案

**6.30(游戏:双骰子赌博)执双骰子游戏是赌场中非常流行的骰子游戏。编写程序,玩这个游戏的一个变种,如下所描述:
执两个骰子。每个骰子有六个面,分别表示值1,2,…,6。检查这两个骰子的和。如果和为2、3或12(称为掷骰子(crap)),你就输了;如果和是7或者11(称作自然(natural)),你就赢了;但如果和是其他数字(例如:4、5、6、8、9或者10),就确定了一个点。继续掷骰子,直到掷出一个7或者掷出和刚才相同的点数。如果掷出的是7,你就输了。如果掷出的点数和你前一次掷出的点数相同,你就赢了。程序扮演一个独立的玩家。

下面是一些运行示例:

You rolled 5 + 6 = 11

You win

You rolled 1 + 2 = 3

You lose

You rolled 4 + 4 = 8

point is 8

You rolled 6 + 2 = 8

You win

You rolled 3 + 2 = 5

point is 5

You rolled 2 + 5 = 7

You lose

**6.30(Game: craps)Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows:Roll two dice. Each die has six faces representing values 1, 2, . . ., and 6, respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose; if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e., 4, 5, 6, 8, 9, or 10), a point is established. Continue to roll the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win. Your program acts as a single player.

Here are some sample runs.

You rolled 5 + 6 = 11

You win

You rolled 1 + 2 = 3

You lose

You rolled 4 + 4 = 8

point is 8

You rolled 6 + 2 = 8

You win

You rolled 3 + 2 = 5

point is 5

You rolled 2 + 5 = 7

You lose

下面是参考答案代码:

public class Ans6_30_page203 {
    public static void main(String[] args) {
        int guessOne = random(6);
        int guessTwo = random(6);
        int guessThree = 0;
        int sum = guessOne + guessTwo;
        int guessTemp = 0;
        boolean nextGuess = true;

        System.out.println("You rolled "+ guessOne +" + "+ guessTwo + " = "+sum);
        if (sum == 7 || sum == 11)
            System.out.println("You win");
        else if (sum == 2 || sum == 3 || sum == 12)
            System.out.println("You lose");
        else {
            while (nextGuess) {
                System.out.println("point is "+sum);
                guessThree = random(6);
                if (guessThree == 7) {
                    System.out.println("You rolled 7 + "+guessThree+" = "+(guessThree*2));
                    System.out.println("You win");
                    nextGuess = false;
                } else if (guessThree == guessOne  || guessThree == guessTwo || guessThree
                == guessTemp) {
                    System.out.println("You rolled "+guessThree+" + "+guessThree+" = "+(guessThree*2));
                    System.out.println("You win");
                    nextGuess = false;
                }else {
                    System.out.println("You rolled "+guessThree+" + "+sum+" = "+(guessThree+sum));
                    System.out.println("You lose");
                    break;
                }
                guessTemp = guessThree;
            }
        }
    }
    public static int random(int guess) {
        return 1 + (int)(Math.random()*guess+1);
    }

}

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

第六章第二十九题(双素数)(Twin primes) – 编程练习题答案

**6.29(双素数)双素数是指一对差值为2的素数。例如:3和5就是一对双素数,5和7是一对双素数,而11和13也是一对双素数。编写程序,找出小于1000的所有双素数。如下所示显示结果:

(3,5)

(5,7)

**6.29(Twin primes)(Twin primes) Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are twin primes. Write a program to find all twin primes less than 1,200. Display the output as follows:

(3,5)

(5,7)

下面是参考答案代码:

public class Ans6_29_page203 {
    public static void main(String[] args) {
        for (int p = 3; p+2 < 1000; p++) {
            if (isPrime(p) && isPrime(p+2))
                System.out.println("("+p+","+(p+2)+")");
        }
    }

    public static boolean isPrime(double number) {
        boolean isPrime = true;
        for (int divisor = 2; divisor <= number / 2; divisor++) {
            if (number % divisor == 0) {
                isPrime = false;
                break;
            }
        }
        return isPrime;
    }
}

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

第六章第二十八题(梅森素数)(Mersenne prime) – 编程练习题答案

**6.28(梅森素数)如果一个素数可以写成的形式,其中p是某个正整数,那么这个素数就称作梅森素数。编写程序,找出p31的所有梅森素数,然后如下显示输入结果:

**6.28(Mersenne prime) A prime number is called a Mersenne prime if it can be written in the form  for some positive integer p. Write a program that finds all Mersenne primes with p  31 and displays the output as follows:

下面是参考答案代码:

public class Ans6_28_page203 {
    public static void main(String[] args) {
        System.out.printf("%-15s%5s%s", "p", "2^p-1", "\n--------------------\n");

        double masonPrime;
        for (int p = 2; p <= 31; p++) {
            masonPrime = Math.pow(2,p)-1;
            if (isPrime(masonPrime))
                System.out.printf("%-15d%1.0f\n",p,masonPrime);
        }
    }

    public static boolean isPrime(double number) {
        boolean isPrime = true;
        for (int divisor = 2; divisor <= number / 2; divisor++) {
            if (number % divisor == 0) {
                isPrime = false;
                break;
            }
        }
    return isPrime;
    }
}

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

第六章第二十七题(反素数)(Emirp) – 编程练习题答案

**6.27(反素数)反素数(反转拼写的素数)是指一个非回文素数,将其反转之后也是一个素数。例如:17是一个素数,而31也是一个素数,所以17和71是反素数。编写程序,显示前100个反素数。每行显示10个,并且数字间用空格隔开,如下所示:

13 17 31 37 71 73 79 97 107 113

149 157 167 179 199 311 337 347 359 389

**6.27(Emirp)An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 120 emirps. Display 10 numbers per line, separated by exactly one space, as follows:

13 17 31 37 71 73 79 97 107 113

149 157 167 179 199 311 337 347 359 389

下面是参考答案代码:

public class Ans6_27_page202 {
    public static void main(String[] args) {
        ReverseePrime(100,10);
    }
    public static void ReverseePrime(int n, int line) {
        int count = 0; // Count the number of prime numbers
        int number = 2; // A number to be tested for primeness

        System.out.println("The first "+n+" numbers are \n");

        // Repeatedly find prime numbers
        while (count < n) {
            String strNumber = number+"";
            // Assume the number is prime
            boolean isPrime = true; // Is the current number prime?

            // Test if number is prime
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                if (number % divisor == 0) { // If true, number is not prime
                    isPrime = false; // Set isPrime to false
                    break; // Exit the for loop
                }
            }

            // Test if number is palindrome
            boolean isPalindrome = true;
            //String strNumber = number+"";
            int low = 0;
            int high = strNumber.length() - 1;
            while (low < high) {
                if (strNumber.charAt(low) != strNumber.charAt(high)) {
                    isPalindrome = false;
                    break;
                }
                low++;
                high--;
            }

            // reverseNumber
            int tempNumber = number;
            String strReverseNumber = "";
            while (tempNumber != 0) {
                strReverseNumber += tempNumber % 10;
                tempNumber /=10;
            }
            int reverseNumber = Integer.parseInt(strReverseNumber);
            // ReverseePrime
            boolean isReverseePrime = true;
            for (int divisor = 2; divisor <= reverseNumber / 2; divisor++) {
                if (reverseNumber % divisor == 0) {
                    isReverseePrime = false;
                    break;
                }
            }

            // Print the prime number and increase the count
            if (isPrime && !isPalindrome && isReverseePrime) {
                count++; // Increase the count

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

            // Check if the next number is prime
            number++;
        }
    }
}

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

第六章第二十六题(回文素数)(Palindromic prime) – 编程练习题答案

**6.26(回文素数)回文素数是指一个数同时为素数和回文数。例如:131是一个素数,同时也是一个回文素数。数学313和757也是如此。编写程序,显示前100个回文素数。每行显示10个数,数字中间用一个空格隔开。如下所示:

2 3 5 7 11 101 131 151 181 191

313 353 373 383 727 757 787 797 919 929

**6.26(Palindromic prime) A palindromic prime is a prime number and also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 120 palindromic prime numbers. Display 10 numbers per line, separated by exactly one space, as follows:

2 3 5 7 11 101 131 151 181 191

313 353 373 383 727 757 787 797 919 929

下面是参考答案代码:

public class Ans6_26_page202 {
    public static void main(String[] args) {
        isPrime(100,10);
    }
    public static void isPrime(int n, int line) {
        int count = 0; // Count the number of prime numbers
        int number = 2; // A number to be tested for primeness

        System.out.println("The first "+n+" numbers are \n");

        // Repeatedly find prime numbers
        while (count < n) {
            // Assume the number is prime
            boolean isPrime = true; // Is the current number prime?

            // Test if number is prime
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                if (number % divisor == 0) { // If true, number is not prime
                    isPrime = false; // Set isPrime to false
                    break; // Exit the for loop
                }
            }

            // Test if number is palindrome
            boolean isPalindrome = true;
            String strNumber = number+"";
            int low = 0;
            int high = strNumber.length() - 1;
            while (low < high) {
                if (strNumber.charAt(low) != strNumber.charAt(high)) {
                    isPalindrome = false;
                    break;
                }
                low++;
                high--;
            }

            // Print the prime number and increase the count
            if (isPrime && isPalindrome) {
                count++; // Increase the count

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

            // Check if the next number is prime
            number++;
        }
    }
}

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

第六章第二十五题(将毫秒数转换成小时数、分钟数和秒数)(Convert milliseconds to hours, minutes, and seconds) – 编程练习题答案

**6.25(将毫秒数转换成小时数、分钟数和秒数)使用下面的方法头,编写一个将毫秒数转换成小时数、分钟数和秒数的方法。

public static String convertMillis(long millis)

该方法返回形如“小时:分钟:秒”的字符串。例如:convertMillis(5500)返回字符串0:0:5,convertMillis(100000)返回字符串0:1:40,convertMillis(555550000)返回字符串154:19:10。编写一个测试程序,提示用户输入一个long型的毫秒数,以“小时:分钟:秒”的格式显示一个字符串。

**6.25(Convert milliseconds to hours, minutes, and seconds)Write a method that converts milliseconds to hours, minutes, and seconds using the following header:

public static String convertMillis(long millis)

The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000)returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10. Write a test program that prompts the user to enter a long integer for milliseconds and displays a string in the format of hours:minutes:seconds.

下面是参考答案代码:

public class Ans6_25_page202 {
    public static void main(String[] args) {
        System.out.println(convertMillis(555550000));
        System.out.println(convertMillis(100000));
        System.out.println(convertMillis(5500));
    }
    public static String convertMillis(long millis) {
        long totalSecond = millis / 1000;
        long currentSecond = totalSecond % 60;
        long totalMinute = totalSecond / 60;
        long currentMinute = totalMinute % 60;
        long totalHour = totalMinute / 60;
        return totalHour+":"+currentMinute+":"+currentSecond;
    }
}

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

第六章第二十四题(显示当前日期和时间)(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版)