## 第七章第五题（打印不同的教）(Print distinct numbers) – 编程练习题答案

Write a program that reads in ten numbers and displays
the number of distinct numbers and the distinct numbers separated by exactly one
space (i.e., if a number appears multiple times, it is displayed only once). (Hint:
Read a number and store it to an array if it is new. If the number is already in the
array, ignore it.) After the input, the array contains the distinct numbers.

``````// 缺陷版本
import java.util.Arrays;
import java.util.Scanner;

public class Ans7_5_page236 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] numberList = new int[10];
// int[] distinctList = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
int[] distinctList = new int[10];
Arrays.fill(distinctList,-1);

for (int i = 0; i < 10; i++)
numberList[i] = input.nextInt();

for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10;j++) {
if (i == numberList[j])
distinctList[i] = numberList[j];
}
}

int count = 0;
for (int i = 0; i < 10; i++) {
if (distinctList[i] != -1)
count++;
}
System.out.print("The number of distinct number is " + count+
"\nThe distinct numbers are: ");

for (int i = 0; i < 10; i++) {
if (distinctList[i] != -1) {
System.out.print(distinctList[i] + " ");
}
}
}
}

// 完善版本
import java.util.Arrays;
import java.util.Scanner;

public class Ans7_5_page236 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] numberList = new int[10];

int maxInt = -99;
for (int i = 0; i < 10; i++) {
numberList[i] = input.nextInt();
if (numberList[i] > maxInt)
maxInt = numberList[i];
}

int[] distinctList = new int[maxInt];
Arrays.fill(distinctList, -99);

int disNum = 0;
for (int i = 0; i < maxInt; i++) {
for (int j = 0; j < 10; j++) {
if (i == numberList[j])
distinctList[i] = numberList[j];
else if (distinctList[i] != -99)
disNum = distinctList[i];
}
}

int count = 0;
for (int i = 0; i < maxInt; i++) {
if (distinctList[i] != -99) {
count++;
}
}
System.out.print("The number of distinct number is " + disNum +
"\nThe distinct numbers are: ");

for (int i = 0; i < maxInt; i++) {
if (distinctList[i] != -99) {
System.out.print(distinctList[i] + " ");
}
}
System.out.print(maxInt);
}
}

//        Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
//        The number of distinct number is 5
//        The distinct numbers are: 1 2 3 4 5 6

//        Enter ten numbers: 11 22 33 22 11 66 33 44 55 67
//        The number of distinct number is 66
//        The distinct numbers are: 11 22 33 44 55 66 67``````

## 第七章第四题（分析成绩）(Analyze scores) – 编程练习题答案

Write a program that reads an unspecified number of scores and
determines how many scores are above or equal to the average and how many
scores are below the average. Enter a negative number to signify the end of the
input. Assume that the maximum number of scores is 100.

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

public class Ans7_4_page236 {
public static void main(String[] args) {
double[] scoreList = new double[100];
Scanner input = new Scanner(System.in);
System.out.print("Enter scores: (negative number signifies end): ");
int count= 0;double score;
do {
score = input.nextDouble();
scoreList[count] = score;
count++;
}while (score >= 0);

double average,sum = 0;
for (int i = 0; i < count-1; i++)
sum += scoreList[i];

average = sum / (count - 1);
System.out.println("Average of scores: "+average);
int minAverge = 0;
int maxAverge = 0;
for (int i = 0; i < count-1; i++) {
if (scoreList[i] >= average)
minAverge++;
else
maxAverge++;
}
System.out.println("Number of scores above or equal to average: " +minAverge+
"\n"+"Number of scores below average: "+(maxAverge));
}
}``````

## 第七章第三题（计算数字的出现次数）(Count occurrence of numbers) – 编程练习题答案

Write a program that reads the integers between 1and 100 and counts the occurrences of each. Assume the input ends with 0.Note that if a number occurs more than one time, the plural word “times” is used

in the output.

``````Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time``````

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

public class Ans7_3_page236 {
public static void main(String[] args) {
int[] number = new int [101];
Scanner input = new Scanner(System.in);
int num;
System.out.print("Enter the integers between 1 and 100: ");
do {
num = input.nextInt();
number[num] = number[num] + 1;
}
while (num != 0);
for (int i = 1; i < number.length; i++) {
if (number[i] == 1) {
System.out.println(i + " occurs " + number[i] + " time");
}else if (number[i] > 1)
System.out.println(i + " occurs " + number[i] + " times");
}
}
}``````

## 第七章第二题（倒置输入的数）(Reverse the numbers entered) – 编程练习题答案

Write a program that reads ten integers and displays
them in the reverse of the order in which they were read.

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

public class Ans7_2_page236 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 integers: ");
int[] number = new int[10];
for (int i = 0; i < 10; i++) {
number[i] = input.nextInt();
}
for (int i = 9; i >= 0; i--)
System.out.print(number[i]+" ");
}
}``````

(指定等级）编写一个程序，读入学生成绩，获取最髙分best, 然后根据下面的规则陚等级值

• 如果分数>=best-10, 等级为A

• 如果分数>=best-20, 等级为B

• 如果分数>=best-30, 等级为C

• 如果分数>=best-40, 等级为D

• 其他情况下，等级为F

``````Enter the number of students: 4
Enter 4 scores: 40 55 70 58
Student 0 score is 40 and grade is C
Student 1 score is 55 and grade is B
Student 2 score is 70 and grade is A
Student 3 score is 58 and grade is B``````

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

public class Ans7_1_page235 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int number = input.nextInt();
System.out.print("Enter " + number + " scores: ");

int[] score = new int[number];
for (int i = 0; i < number; i++)
score[i] = input.nextInt();

int[] scoreSort = new int[number];
System.arraycopy(score,0,scoreSort,0,score.length);

Arrays.sort(scoreSort);

int maxSort = scoreSort[number-1];
for (int i = 0; i < number; i++) {
if (score[i] >= maxSort-10)
System.out.println("Student " + i + " score is " + score[i] +
else if (score[i] >= maxSort-20)
System.out.println("Student " + i + " score is " + score[i] +
else if (score[i] >= maxSort-30)
System.out.println("Student " + i + " score is " + score[i] +
else if (score[i] >= maxSort-40)
System.out.println("Student " + i + " score is " + score[i] +
else
System.out.println("Student " + i + " score is " + score[i] +
}
}
}``````

## 第六章第三十九题（几何：点的位置）(Geometry: point position) – 编程练习题答案

6.39（几何：点的位置）编程练习题3.32显示如何测试一个点是否在一个有向直线的左侧、右侧，或在该直线上。使用下面的方法头编写该方法：

public static boolean leftOfTheLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheSameLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheLineSegment(double x0, double y0, double x1, double y1, double x2, double y2)

Enter three points for p0, p1, and p2: 1 1 2 2 1.5 1.5

(1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 3 3

(3.0, 3.0) is on the same line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 1.5

(1.0, 1.5) is on the left side of the line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 –1

(1.0, −1.0) is on the right side of the line from (1.0, 1.0) to (2.0, 2.0)

6.39(Geometry: point position) Programming Exercise 3.32 shows how to test whether a point is on the left side of a directed line, on the right, or on the same line. Write the methods with the following headers:

public static boolean leftOfTheLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheSameLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheLineSegment(double x0, double y0, double x1, double y1, double x2, double y2)

Write a program that prompts the user to enter the three points for p0, p1, and p2and displays whether p2 is on the left side of the line from p0 to p1, right side, the same line, or on the line segment.

Here are some sample runs:

Enter three points for p0, p1, and p2: 1 1 2 2 1.5 1.5

(1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 3 3

(3.0, 3.0) is on the same line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 1.5

(1.0, 1.5) is on the left side of the line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 –1

(1.0, −1.0) is on the right side of the line from (1.0, 1.0) to (2.0, 2.0)

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

public class Ans6_39_page205 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three points for p0, p1, and p2:");
double x0 = input.nextDouble();
double y0 = input.nextDouble();
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();

if (onTheSameLine(x0, y0, x1, y1, x2, y2)) {
if (onTheLineSegment(x0, y0, x1, y1, x2, y2)) {
System.out.printf("(%.1f, %.1f) is on the line segment from "
+ "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
} else {
System.out.printf("(%.1f, %.1f) is on the same line from "
+ "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
}
} else {
if (leftOfTheLine(x0, y0, x1, y1, x2, y2)) {
System.out.printf("(%.1f, %.1f) is on the left side of the line from "
+ "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
} else {
System.out.printf("(%.1f, %.1f) is on the right side of the line from "
+ "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
}
}
}

public static boolean leftOfTheLine(double x0, double y0,
double x1, double y1, double x2, double y2) {
if ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) > 0)
return true;
else
return false;
}

public static boolean onTheSameLine(double x0, double y0,
double x1, double y1, double x2, double y2) {
return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) == 0;
}

public static boolean onTheLineSegment(double x0, double y0,
double x1, double y1, double x2, double y2) {
if ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) == 0 &&
x2 <= (Math.max(x0, x1)) && x2 >= (Math.min(x1, x0)))
return true;
else
return false;
}
}``````

## 第六章第三十八题（生成随机字符）(Generate random characters) – 编程练习题答案

*6.38（生成随机字符）使用程序清单6-10RandomCharacter中的方法，打印100个大写字母及100个一位数字，每行打印10个。

*6.38(Generate random characters) Use the methods in RandomCharacter in Listing 6.10 to print 100 uppercase letters and then 100 single digits, printing ten per line.

``````// https://cn.fankuiba.com
public class Ans6_38_page205 {
public static void main(String[] args) {
for (int count = 1; count <=100; count++) {
System.out.print(getRandomUpperCaseLetter()+""+getRandomDigitCharacter());
if (count * 2 % 10 == 0)
System.out.println();
}
}
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}

/** Generate a random uppercase letter */
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}

/** Generate a random digit character */
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
}``````

## 第六章第三十二题（游戏：赢取双骰子赌博游戏的机会）(Game: chance of winning at craps) – 编程练习题答案

**6.32（游戏：赢取双骰子赌博游戏的机会）修改编程练习题6.30使该程序运行10000次，然后显示赢得游戏的次数

**6.32(Game: chance of winning at craps)Revise Exercise 6.30 to run it 15,000 times and display the number of winning games.

``````// https://cn.fankuiba.com
public class Ans6_32_page205 {
public static void main(String[] args) {
int count = 0;
for (int c = 0; c < 10000; c++) {
int guessOne = random(6);
int guessTwo = random(6);
int guessThree;
int sum = guessOne + guessTwo;
int guessTemp = 0;
boolean nextGuess = true;

//System.out.println("You rolled " + guessOne + " + " + guessTwo + " = " + sum);
if (sum == 7 || sum == 11) {
count = count + 1;
//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");
count++;
nextGuess = false;
} else if (guessThree == guessOne || guessThree == guessTwo || guessThree
== guessTemp) {
//System.out.println("You rolled " + guessThree + " + " + guessThree + " = " + (guessThree * 2));
//System.out.println("You win");
count++;
nextGuess = false;
} else {
//System.out.println("You rolled " + guessThree + " + " + sum + " = " + (guessThree + sum));
//System.out.println("You lose");
break;
}
guessTemp = guessThree;
}
}
}
System.out.println(count);
}

public static int random(int guess) {
return 1 + (int) (Math.random() * guess + 1);
}
}``````

## 第六章第三十三题（当前日期和时间）(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);
}
}
}``````