## 第六章第三十三题（当前日期和时间）(Current date and time) – 编程练习题答案

**6.33（当前日期和时间）调用System.currentTimeMillis()返回从1970年1月1日0点开始至今为止的毫秒数。编写程序，显示当前日期和时间。

Current date and time is May 16, 2012 10:34:23

**6.33(Current date and time) Invoking System.currentTimeMillis() returns the elapsed time in milliseconds since midnight of January 1, 1970. Write a program that displays the date and time.
Here is a sample run:

Current date and time is May 16, 2012 10:34:23

``````// https://cn.fankuiba.com
public class Ans6_33_page205 {
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;
}

// IntMonthToStrMonth
String strCurrentMonths = "";
switch (currentMonths) {
case 1:
strCurrentMonths = "January";break;
case 2:
strCurrentMonths = "February";break;
case 3:
strCurrentMonths = "March";break;
case 4:
strCurrentMonths = "April";break;
case 5:
strCurrentMonths = "May";break;
case 6:
strCurrentMonths = "June";break;
case 7:
strCurrentMonths = "July";break;
case 8:
strCurrentMonths = "August";break;
case 9:
strCurrentMonths = "September";break;
case 10:
strCurrentMonths = "October";break;
case 11:
strCurrentMonths = "November";break;
case 12:
strCurrentMonths = "December";
}

// Display results
System.out.println("Current date and time is " + strCurrentMonths
+" "+currentDay+", "+currentYear+" "+
currentHour+":"+currentMinute+":"+currentSecond);
}

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

## 第六章第三十四题（打印日历）(Print calendar) – 编程练习题答案

**6.34（打印日历）编程练习题3.21使用Zeller一致性原理来计算某天是星期几。使用Zeller的算法简化程序清单6-12以获得每月开始的第一天是星期几。

**6.34(Print calendar) Programming Exercise 3.21 uses Zeller’s congruence to calculate the day of the week. Simplify Listing 6.12, PrintCalendar.java, using Zeller’s algorithm to get the start day of the month.

``````// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_34_page205 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter full year (e.g., 2012): ");
int year = input.nextInt();
System.out.print("What day is January 1, "+year+" ? ");
int week = input.nextInt();

int month = 1, day = 0;
String monthString = "";
boolean leapYear;

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 && year % 3200 != 0) || year % 172800 == 0)
leapYear = true;
else
leapYear = false;

for (; month <= 12; month++) {
switch (month) {
case 1:
monthString = "January";
break;
case 2:
day += 31;
monthString = "February";
break;
case 3:
monthString = "March";
if (leapYear)
day += 29;
else
day += 28;
break;
case 4:
day += 31;
monthString = "April";
break;
case 5:
day += 30;
monthString = "May";
break;
case 6:
day += 31;
monthString = "June";
break;
case 7:
day += 30;
monthString = "July";
break;
case 8:
day += 31;
monthString = "August";
break;
case 9:
day += 31;
monthString = "September";
break;
case 10:
day += 30;
monthString = "October";
break;
case 11:
day += 31;
monthString = "November";
break;
case 12:
day += 30;
monthString = "December";
}
int days = (week + day) % 7;
System.out.print("\n           " + monthString + " " + year + "\n---------------------------------");
System.out.printf("\n%-5s%-5s%-5s%-5s%-5s%-5s%-5s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

for (int n =1;n<=days;n++) {
System.out.printf("%-5s", "");
}

int j = 1;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 ||
month == 12) {
for (; j <= 31; j++) {
System.out.printf("%-5d", j);
if ((days+j) % 7 == 0)
System.out.println();
}
}
else if (month == 2 && leapYear) {
for (; j <= 29; j++) {
System.out.printf("%-5d", j);
if ((days+j) % 7 == 0)
System.out.println();
}
}
else if (month == 2) {
for (; j <= 28; j++) {
System.out.printf("%-5d", j);
if ((days+j) % 7 == 0)
System.out.println();
}
}
else {
for (; j <= 30; j++) {
System.out.printf("%-5d", j);
if ((days + j) % 7 == 0)
System.out.println();
}
}
System.out.print("\n");
switch (days) {
case 0:
System.out.print("Sun");break;
case 1:
System.out.print("Mon");break;
case 2:
System.out.print("Tue");break;
case 3:
System.out.print("Wed");break;
case 4:
System.out.print("Thu");break;
case 5:
System.out.print("Fri");break;
case 6:
System.out.print("Sat");
}
System.out.println(" starts on the first day of "+monthString);
}
}
}``````

## 第六章第三十五题（几何：五边形的面积）(Geometry: area of a pentagon) – 编程练习题答案

6.35（几何：五边形的面积）五边形的面积可以使用下面的公式计算：

public static double area(double side)

Enter the side:5.5

The area of the pentagon is 52.044441

6.35(Geometry: area of a pentagon)The area of a pentagon can be computed using the following formula:

Write a method that returns the area of a pentagon using the following header:

public static double area(double side)

Write a main method that prompts the user to enter the side of a pentagon and displays its area.

Here is a sample run:

Enter the side:5.5

The area of the pentagon is 52.044441

``````// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_35_page205 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double side = input.nextDouble();
System.out.println("The area of the pentagon is "+area(side));
}
public static double area(double side) {
return  (5 * side * side) / (4 * Math.tan(Math.PI / 5));
}
}``````

## 第六章第三十一题（金融应用：信用卡号的合法性验证）(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是合法的。

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;
}
}``````

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

**6.30（游戏：双骰子赌博）执双骰子游戏是赌场中非常流行的骰子游戏。编写程序，玩这个游戏的一个变种，如下所描述：

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);
}

}``````

## 第六章第二十九题（双素数）(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;
}
}``````

## 第六章第二十八题（梅森素数）(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;
}
}``````

## 第六章第二十七题（反素数）(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++;
}
}
}``````

## 第六章第二十六题（回文素数）(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++;
}
}
}``````

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

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

public static String convertMillis(long millis)

**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;