Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

4.10 (GUI) Controlling a Loop with a Confirmation Dialog 139

26

27if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {

28// Print the number and advance to the new line

29System.out.println(number);

30}

31else

32System.out.print(number + " ");

33}

34

35// Check if the next number is prime

36number++;

37}

38}

39}

The first 50 prime numbers are

2 3 5 7 11

13 17 19

23 29

 

31

37 41

43 47 53

59 61

67 71

73

79 83

89 97 101 103 107 109 113

127 131 137 139 149

151

157

163 167 173

179 181 191 193 197

199

211

223 227 229

This is a complex program for novice programmers. The key to developing a programmatic

solution to this problem, and to many other problems, is to break it into subproblems and subproblem develop solutions for each of them in turn. Do not attempt to develop a complete solution in

the first trial. Instead, begin by writing the code to determine whether a given number is prime, then expand the program to test whether other numbers are prime in a loop.

To determine whether a number is prime, check whether it is divisible by a number between 2 and number/2 inclusive (line 16). If so, it is not a prime number (line 18); otherwise, it is a prime number. For a prime number, display it. If the count is divisible by 10 (lines 27–30), advance to a new line. The program ends when the count reaches 50.

The program uses the break statement in line 19 to exit the for loop as soon as the number is found to be a nonprime. You can rewrite the loop (lines 16–21) without using the break statement, as follows:

for (int divisor = 2; divisor <= number / 2 && isPrime; divisor++) {

// If true, the number is not prime if (number % divisor == 0) {

// Set isPrime to false, if the number is not prime isPrime = false;

}

}

However, using the break statement makes the program simpler and easier to read in this case.

4.10 (GUI) Controlling a Loop with a Confirmation Dialog

A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes confirmation dialog or No continue or terminate the loop. The template of the loop may look as follows:

int option = JOptionPane.YES_OPTION; while (option == JOptionPane.YES_OPTION) {

System.out.println("continue loop");

option = JOptionPane.showConfirmDialog(null, "Continue?");

}

140 Chapter 4 Loops

Listing 4.15 rewrites Listing 4.4, SentinelValue.java, using a confirmation dialog box. A sample run is shown in Figure 4.4.

(a)

(b)

(c)

(d)

(e)

FIGURE 4.4 The user enters 3 in (a), clicks Yes in (b), enters 5 in (c), clicks No in (d), and the result is shown in (e).

LISTING 4.15 SentinelValueUsingConfirmationDialog.java

 

1

import javax.swing.JOptionPane;

 

2

 

 

3

public class SentinelValueUsingConfirmationDialog {

 

4

public static void main(String[] args) {

 

5

int sum = 0;

 

6

 

 

7

// Keep reading data until the user answers No

confirmation option

8

int option = JOptionPane.YES_OPTION;

check option

9

while (option == JOptionPane.YES_OPTION) {

 

10

// Read the next data

input dialog

11

String dataString = JOptionPane.showInputDialog(

 

12

"Enter an int value: ");

 

13

int data = Integer.parseInt(dataString);

 

14

 

 

15

sum += data;

 

16

 

confirmation dialog

17

option = JOptionPane.showConfirmDialog(null, "Continue?");

 

18

}

 

19

 

message dialog

20

JOptionPane.showMessageDialog(null, "The sum is " + sum);

 

21

}

 

22

}

 

A program displays an input dialog to prompt the user to enter an integer (line 11) and adds it

 

to sum (line 15). Line 17 displays a confirmation dialog to let the user decide whether to con-

 

tinue the input. If the user clicks Yes, the loop continues; otherwise the loop exits. Finally the

 

program displays the result in a message dialog box (line 20).

KEY TERMS

break statement

136

for loop 126

continue statement 136

loop control structure 127

do-while loop

124

infinite loop 117

Chapter Summary 141

input redirection

124

loop body 116

 

iteration 116

 

nested loop

129

 

labeled continue statement 136

off-by-one error

124

loop 116

 

output redirection

124

loop-continuation-

sentinel value

122

condition

116

while loop

116

 

CHAPTER SUMMARY

1.There are three types of repetition statements: the while loop, the do-while loop, and the for loop.

2.The part of the loop that contains the statements to be repeated is called the loop body.

3.A one-time execution of a loop body is referred to as an iteration of the loop.

4.An infinite loop is a loop statement that executes infinitely.

5.In designing loops, you need to consider both the loop control structure and the loop body.

6.The while loop checks the loop-continuation-condition first. If the condition is true, the loop body is executed; if it is false, the loop terminates.

7.The do-while loop is similar to the while loop, except that the do-while loop executes the loop body first and then checks the loop-continuation-condition to decide whether to continue or to terminate.

8.Since the while loop and the do-while loop contain the loop-continuation- condition, which is dependent on the loop body, the number of repetitions is determined by the loop body. The while loop and the do-while loop often are used when the number of repetitions is unspecified.

9.A sentinel value is a special value that signifies the end of the loop.

10.The for loop generally is used to execute a loop body a predictable number of times; this number is not determined by the loop body.

11.The for loop control has three parts. The first part is an initial action that often initializes a control variable. The second part, the loop-continuation-condition, determines whether the loop body is to be executed. The third part is executed after each iteration and is often used to adjust the control variable. Usually, the loop control variables are initialized and changed in the control structure.

12.The while loop and for loop are called pretest loops because the continuation condition is checked before the loop body is executed.

13.The do-while loop is called posttest loop because the condition is checked after the loop body is executed.

14.Two keywords, break and continue, can be used in a loop.

142 Chapter 4 Loops

15.The break keyword immediately ends the innermost loop, which contains the break.

16.The continue keyword only ends the current iteration.

REVIEW QUESTIONS

Sections 4.2–4.4

4.1Analyze the following code. Is count < 100 always true, always false, or sometimes true or sometimes false at Point A, Point B, and Point C?

int count = 0;

while (count < 100) { // Point A

System.out.println("Welcome to Java!\n"); count++;

// Point B

}

//Point C

4.2What is wrong if guess is initialized to 0 in line 11 in Listing 4.2?

4.3How many times is the following loop body repeated? What is the printout of the loop?

int i = 1;

 

int i = 1;

 

int i = 1;

while (i < 10)

 

while (i < 10)

 

while (i < 10)

if (i % 2 == 0)

 

if (i % 2 == 0)

 

if ((i++) % 2 == 0)

System.out.println(i);

 

System.out.println(i++);

 

System.out.println(i);

 

 

 

 

 

(a)

 

(b)

 

(c)

4.4What are the differences between a while loop and a do-while loop? Convert the following while loop into a do-while loop.

int sum = 0;

int number = input.nextInt(); while (number != 0) {

sum += number;

number = input.nextInt();

}

4.5Do the following two loops result in the same value in sum?

for (int i = 0; i < 10; ++i ) { sum += i;

}

(a)

for (int i = 0; i < 10; i++ ) { sum += i;

}

(b)

4.6What are the three parts of a for loop control? Write a for loop that prints the numbers from 1 to 100.

4.7Suppose the input is 2 3 4 5 0. What is the output of the following code?

import java.util.Scanner;

public class Test {

Review Questions 143

public static void main(String[] args) { Scanner input = new Scanner(System.in);

int number, max;

number = input.nextInt(); max = number;

while (number != 0) { number = input.nextInt(); if (number > max)

max = number;

}

System.out.println("max is " + max); System.out.println("number " + number);

}

}

4.8Suppose the input is 2 3 4 5 0. What is the output of the following code?

import java.util.Scanner;

public class Test {

public static void main(String[] args) { Scanner input = new Scanner(System.in);

int number, sum = 0, count;

for (count = 0; count < 5; count++) { number = input.nextInt();

sum += number;

}

System.out.println("sum is " + sum); System.out.println("count is " + count);

}

}

4.9Suppose the input is 2 3 4 5 0. What is the output of the following code?

import java.util.Scanner;

public class Test {

public static void main(String[] args) { Scanner input = new Scanner(System.in);

int number, max;

number = input.nextInt(); max = number;

do {

number = input.nextInt(); if (number > max)

max = number;

} while (number != 0);

System.out.println("max is " + max); System.out.println("number " + number);

}

}

144 Chapter 4 Loops

4.10

What does the following statement do?

for ( ; ; ) { do something;

}

4.11If a variable is declared in the for loop control, can it be used after the loop exits?

4.12Can you convert a for loop to a while loop? List the advantages of using for loops.

4.13Convert the following for loop statement to a while loop and to a do-while loop:

long sum = 0;

for (int i = 0; i <= 1000; i++) sum = sum + i;

4.14Will the program work if n1 and n2 are replaced by n1 / 2 and n2 / 2 in line 17 in Listing 4.8?

Section 4.9

4.15What is the keyword break for? What is the keyword continue for? Will the following program terminate? If so, give the output.

int balance = 1000;

 

int balance = 1000;

while (true) {

 

while (true) {

if (balance < 9)

 

if (balance < 9)

break;

 

continue;

balance = balance - 9;

 

balance = balance - 9;

}

 

}

System.out.println("Balance is "

 

System.out.println("Balance is "

+ balance);

 

+ balance);

 

 

 

(a)

 

(b)

4.16Can you always convert a while loop into a for loop? Convert the following while loop into a for loop.

int i = 1; int sum = 0;

while (sum < 10000) { sum = sum + i;

i++;

}

4.17The for loop on the left is converted into the while loop on the right. What is wrong? Correct it.

for (int i = 0; i < 4; i++) { if (i % 3 == 0) continue; sum += i;

}

Converted

 

int i

= 0;

 

while

(i

< 4) {

Wrong

if(i %

3

== 0) continue;

conversion

sum

+=

i;

 

 

 

i++;

 

 

 

 

 

}

 

 

 

 

 

 

 

 

 

Review Questions 145

4.18Rewrite the programs TestBreak and TestContinue in Listings 4.11 and 4.12 without using break and continue.

4.19After the break statement is executed in the following loop, which statement is executed? Show the output.

for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) {

if (i * j > 2) break;

System.out.println(i * j);

}

System.out.println(i);

}

4.20After the continue statement is executed in the following loop, which statement is executed? Show the output.

for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) {

if (i * j > 2) continue;

System.out.println(i * j);

}

System.out.println(i);

}

Comprehensive

4.21Identify and fix the errors in the following code:

1 public class Test {

2 public void main(String[] args) { 3 for (int i = 0; i < 10; i++); 4 sum += i;

5

6if (i < j);

7System.out.println(i)

8else

9

System.out.println(j);

10

 

11while (j < 10);

12{

13j++;

14};

15

16do {

17j++;

18} while (j < 10)

19}

20}

146 Chapter 4 Loops

4.22What is wrong with the following programs?

1

public class ShowErrors {

1

public class ShowErrors {

2

public static void main(String[] args) {

2

public static void main(String[] args) {

3

int i;

3

for (int i = 0; i < 10; i++);

4

int j = 5;

4

System.out.println(i + 4);

5

 

5

}

6

if (j > 3)

6

}

7System.out.println(i + 4);

8

}

9

}

(a)

(b)

4.23Show the output of the following programs. (Tip: Draw a table and list the variables in the columns to trace these programs.)

public class Test {

/** Main method */

public static void main(String[] args) { for (int i = 1; i < 5; i++) {

int j = 0; while (j < i) {

System.out.print(j + " "); j++;

}

}

}

}

(a)

public class Test {

public static void main(String[] args) { int i = 5;

while (i >= 1) { int num = 1;

for (int j = 1; j <= i; j++) { System.out.print(num + "xxx"); num *= 2;

}

System.out.println(); i--;

}

}

}

(c)

public class Test {

/** Main method */

public static void main(String[] args) { int i = 0;

while (i < 5) {

for (int j = i; j > 1; j-) System.out.print(j + " ");

System.out.println("****"); i++;

}

}

}

(b)

public class Test {

public static void main(String[] args) { int i = 1;

do {

int num = 1;

for (int j = 1; j <= i; j++) { System.out.print(num + "G"); num += 2;

}

System.out.println();

i++;

} while (i <= 5);

}

}

(d)

4.24What is the output of the following program? Explain the reason.

int x = 80000000;

while (x > 0) x++;

System.out.println("x is " + x);

4.25Count the number of iterations in the following loops.

Programming Exercises 147

int count = 0; while (count < n) {

count++;

}

(a)

int count = 5; while (count < n) {

count++;

}

for (int count = 0;

count <= n; count++) {

}

(b)

int count = 5; while (count < n) {

count = count + 3;

}

(c) (d)

PROGRAMMING EXERCISES

Pedagogical Note

For each problem, read it several times until you understand the problem. Think how to solve

 

the problem before coding. Translate your logic into a program.

read and think before coding

A problem often can be solved in many different ways. Students are encouraged to explore

 

various solutions.

explore solutions

Sections 4.2–4.7

4.1* (Counting positive and negative numbers and computing 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:

Enter an int value, the

program exits if the input is 0:

 

1 2 -1 3 0

 

 

 

 

The number of positives

is 3

The number of negatives

is 1

The total is 5

 

The average is 1.25

 

 

 

 

 

 

 

4.2(Repeating additions) Listing 4.3, SubtractionQuizLoop.java, generates five random subtraction questions. Revise the program to generate ten random addition questions for two integers between 1 and 15. Display the correct count and test time.

4.3(Conversion from kilograms to pounds) Write a program that displays the following table (note that 1 kilogram is 2.2 pounds):

Kilograms Pounds

12.2

3

6.6

...

 

197

433.4

199

437.8

148 Chapter 4 Loops

4.4(Conversion from miles to kilometers) Write a program that displays the following table (note that 1 mile is 1.609 kilometers):

Miles Kilometers

11.609

2

3.218

...

 

914.481

10 16.090

4.5(Conversion from kilograms to pounds) Write a program that displays the following two tables side by side (note that 1 kilogram is 2.2 pounds):

Kilograms

Pounds

Pounds

Kilograms

1

2.2

20

9.09

3

6.6

25

11.36

...

 

 

 

197

433.4

510

231.82

199

437.8

515

234.09

4.6(Conversion from miles to kilometers) Write a program that displays the following two tables side by side (note that 1 mile is 1.609 kilometers):

Miles

Kilometers

Kilometers

Miles

1

1.609

20

12.430

2

3.218

25

15.538

...

 

 

 

9

14.481

60

37.290

10

16.090

65

40.398

4.7** (Financial application: computing future tuition) Suppose that the tuition for a university is $10,000 this year and increases 5% every year. Write a program that computes the tuition in ten years and the total cost of four years’ worth of tuition starting ten years from now.

4.8(Finding 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.

4.9* (Finding the two highest scores) Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score and the student with the secondhighest score.

4.10(Finding numbers divisible by 5 and 6) Write a program that displays all the numbers from 100 to 1000, ten per line, that are divisible by 5 and 6.

4.11(Finding numbers divisible by 5 or 6, but not both) Write a program that displays all the numbers from 100 to 200, ten per line, that are divisible by 5 or 6, but not both.

4.12(Finding the smallest n such that n2 7 12,000) Use a while loop to find the smallest integer n such that n2 is greater than 12,000.

4.13(Finding the largest n such that n3 6 12,000) Use a while loop to find the largest integer n such that n3 is less than 12,000.

4.14* (Displaying the ACSII character table) Write a program that prints the characters in the ASCII character table from ‘!' to ‘~'. Print ten characters per line. The ASCII table is shown in Appendix B.

Programming Exercises 149

Section 4.8

4.15* (Computing the greatest common divisor) Another solution for Listing 4.8 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.

4.16** (Finding 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.

4.17** (Displaying pyramid) Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the following sample run:

Enter the number of lines: 7

 

 

 

 

 

 

1

 

 

 

 

 

 

 

 

 

 

 

2

1

2

 

 

 

 

 

 

 

 

 

3

2

1

2

3

 

 

 

 

 

 

 

4

3

2

1

2

3

4

 

 

 

 

 

5

4

3

2

1

2

3

4

5

 

 

 

6

5

4

3

2

1

2

3

4

5

6

 

7

6

5

4

3

2

1

2

3

4

5

6

7

4.18* (Printing four patterns using loops) Use nested loops that print the following patterns in four separate programs:

Pattern I

Pattern II

Pattern III

Pattern

IV

1

1 2 3 4 5 6

1

1 2 3 4 5 6

1 2

1 2 3 4 5

2 1

1 2 3 4 5

1 2 3

1 2 3 4

3 2 1

1 2 3 4

1 2 3 4

1 2 3

4 3 2 1

1 2 3

1 2 3 4 5

1 2

5 4 3 2 1

 

1 2

1 2 3 4 5 6

1

6 5 4 3 2 1

 

1

4.19** (Printing numbers in a pyramid pattern) Write a nested for loop that prints the following output:

 

 

 

 

 

 

 

1

 

 

 

 

 

 

 

 

 

 

 

 

 

1

2

1

 

 

 

 

 

 

 

 

 

 

 

1

2

4

2

1

 

 

 

 

 

 

 

 

 

1

2

4

8

4

2

1

 

 

 

 

 

 

 

1

2

4

8

16

8

4

2

1

 

 

 

 

 

1

2

4

8

16

32

16

8

4

2

1

 

 

 

1

2

4

8

16

32

64

32

16

8

4

2

1

 

1

2

4

8

16

32

64

128

64

32

16

8

4

2

1

4.20* (Printing prime numbers between 2 and 1000) Modify Listing 4.14 to print all the prime numbers between 2 and 1000, inclusive. Display eight prime numbers per line.

Comprehensive

4.21** (Financial application: comparing loans with various interest rates) Write a program that lets the user enter the loan amount and loan period in number of years

150 Chapter 4 Loops

and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8. Here is a sample run:

 

 

 

 

 

 

 

Loan Amount:

10000

 

 

 

 

Number of Years:

5

 

 

 

 

Interest Rate

 

 

 

Monthly Payment

Total Payment

5%

 

188.71

11322.74

5.125%

 

189.28

11357.13

5.25%

 

189.85

11391.59

...

 

 

 

 

 

 

7.875%

 

202.17

12129.97

8.0%

 

202.76

12165.83

 

 

 

 

 

 

 

Video Note

Display loan schedule

For the formula to compute monthly payment, see Listing 2.8, ComputeLoan.java.

4.22** (Financial application: loan amortization schedule) The monthly payment for a given loan pays the principal and the interest. The monthly interest is computed by multiplying the monthly interest rate and the balance (the remaining principal). The principal paid for the month is therefore the monthly payment minus the monthly interest. Write a program that lets the user enter the loan amount, number of years, and interest rate and displays the amortization schedule for the loan. Here is a sample run:

Loan Amount: 10000

Number of Years: 1

Annual Interest Rate: 7%

Monthly Payment: 865.26

Total Payment: 10383.21

Payment#

Interest

Principal

Balance

1

58.33

806.93

9193.07

2

53.62

811.64

8381.43

...

 

 

 

11

10.0

855.26

860.27

12

5.01

860.25

0.01

Note

The balance after the last payment may not be zero. If so, the last payment should be the normal monthly payment plus the final balance.

Hint: Write a loop to print the table. Since the monthly payment is the same for each month, it should be computed before the loop. The balance is initially the loan amount. For each iteration in the loop, compute the interest and principal, and update the balance. The loop may look like this:

for (i = 1; i <= numberOfYears * 12; i++) { interest = monthlyInterestRate * balance; principal = monthlyPayment - interest; balance = balance - principal; System.out.println(i + "\t\t" + interest

+ "\t\t" + principal + "\t\t" + balance);

}

Programming Exercises 151

4.23* (Obtaining more accurate results) In computing the following series, you will obtain more accurate results by computing from right to left rather than from left to right:

1 +

1

+

1

+ Á +

1

2

3

n

Write a program that compares the results of the summation of the preceding series, computing from left to right and from right to left with n = 50000.

4.24* (Summing a series) Write a program to sum the following series:

1

+

3

+

5

+

7

+

9

+

11

+ Á +

95

+

97

3

 

 

 

 

 

 

 

5

7

9

11

13

97

99

4.25** (Computing p) You can approximate p by using the following series:

p = 4a1 -

1

+

1

-

1

+

1

-

1

+ Á +

1

-

1

b

3

5

7

9

11

2i - 1

2i + 1

Write a program that displays the p value for i = 10000, 20000, Á , and

100000.

4.26** (Computing e) You can approximate e using the following series:

e = 1 + 1 + 1 + 1 + 1 + Á + 1 1! 2! 3! 4! i!

Write a program that displays the e value for i = 10000, 20000, Á , and

100000.

 

 

1

 

 

1

(Hint: Since i! = i *

(i -

1) * Á * 2 *

 

 

1, then

 

is

 

 

i!

i(i

- 1)!

 

 

 

 

 

Initialize e and item to be 1 and keep adding a new item to e. The new item is the previous item divided by i for i = 2, 3, 4, Á .)

4.27** (Displaying leap years) Write a program that displays all the leap years, ten per line, in the twenty-first century (from 2001 to 2100).

4.28** (Displaying the first days of each month) Write a program that prompts the user to enter the year and first day of the year, and displays the first day of each month in the year on the console. For example, if the user entered the year 2005, and 6 for Saturday, January 1, 2005, your program should display the following output (note that Sunday is 0):

January 1, 2005 is Saturday

...

December 1, 2005 is Thursday

4.29** (Displaying calendars) Write a program that prompts the user to enter the year and first day of the year and displays the calendar table for the year on the console. For example, if the user entered the year 2005, and 6 for Saturday, January 1, 2005, your program should display the calendar for each month in the year, as follows:

January 2005

Sun

Mon

Tue

Wed

Thu

Fri

Sat

 

 

 

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

 

 

 

 

 

...

152 Chapter 4 Loops

December 2005

Sun

Mon

Tue

Wed

Thu

Fri

Sat

 

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

4.30* (Financial application: compound value) Suppose you save $100 each month into a savings account with the annual interest rate 5%. So, the monthly interest rate is 0.05 / 12 = 0.00417. After the first month, the value in the account becomes

100 * (1 + 0.00417) = 100.417

After the second month, the value in the account becomes

(100 + 100.417) * (1 + 0.00417) = 201.252

After the third month, the value in the account becomes

(100 + 201.252) * (1 + 0.00417) = 302.507

and so on.

Write a program that prompts the user to enter an amount (e.g., 100), the annual interest rate (e.g., 5), and the number of months (e.g., 6) and displays the amount in the savings account after the given month.

4.31* (Financial application: computing CD value) Suppose you put $10,000 into a CD with an annual percentage yield of 5.75%. After one month, the CD is worth

10000 + 10000 * 5.75 / 1200 = 10047.91

After two months, the CD is worth

10047.91 + 10047.91 * 5.75 / 1200 = 10096.06

After three months, the CD is worth

10096.06 + 10096.06 * 5.75 / 1200 = 10144.43

and so on.

Write a program that prompts the user to enter an amount (e.g., 10000), the annual percentage yield (e.g., 5.75), and the number of months (e.g., 18) and displays a table as shown in the sample run.

Enter the initial deposit amount: 10000

Enter annual percentage yield: 5.75

Enter maturity period (number of months): 18

Month

CD Value

1

10047.91

2

10096.06

...

 

17

10846.56

18

10898.54

Programming Exercises 153

4.32** (Game: lottery) Revise Listing 3.9, Lottery.java, to generate a lottery of a twodigit number. The two digits in the number are distinct.

(Hint: Generate the first digit. Use a loop to continuously generate the second digit until it is different from the first digit.)

4.33** (Perfect number) A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.

4.34*** (Game: scissor, rock, paper) Exercise 3.17 gives a program that plays the scissor-rock-paper game. Revise the program to let the user continuously play until either the user or the computer wins more than two times.

4.35* (Summation) Write a program that computes the following summation.

1

2

 

1

 

 

1

 

 

1

 

 

 

 

+

2 2

 

 

+

2 2

 

+ Á +

2 2

 

 

1 +

 

 

 

 

+

 

 

 

 

+

 

 

 

 

+

 

 

2

2

3

3

4

624

625

4.36** (Business application: checking ISBN) Use loops to simplify Exercise 3.19. 4.37** (Decimal to binary) Write a program that prompts the user to enter a decimal

integer and displays its corresponding binary value. Don’t use Java’s

Integer.toBinaryString(int) in this program.

4.38** (Decimal to hex) Write a program that prompts the user to enter a decimal integer and displays its corresponding hexadecimal value. Don’t use Java’s

Integer.toHexString(int) in this program.

4.39* (Financial application: finding the sales amount) You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate.

Sales Amount

Commission Rate

$0.01–$5,000

8 percent

$5,000.01–$10,000

10 percent

$10,000.01 and above

12 percent

Your goal is to earn $30,000 a year. Write a program that finds out the minimum amount of sales you have to generate in order to make $30,000.

4.40(Simulation: head or tail) Write a program that simulates flipping a coin one million times and displays the number of heads and tails.

4.41** (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.)

Enter numbers: 3 5 2 5 5 5 0 The largest number is 5

The occurrence count of the largest number is 4

154 Chapter 4 Loops

4.42* (Financial application: finding the sales amount) Rewrite Exercise 4.39 as follows:

Use a for loop instead of a do-while loop.

Let the user enter COMMISSION_SOUGHT instead of fixing it as a constant.

4.43* (Simulation: clock countdown) Write a program that prompts the user to enter the number of seconds, displays a message at every second, and terminates when the time expires. Here is a sample run:

Enter the number of second: 3 2 seconds remaining

1 second remaining Stopped

4.44** (Monte Carlo simulation) A square is divided into four smaller regions as shown below in (a). If you throw a dart into the square 1000000 times, what is the probability for a dart to fall into an odd-numbered region? Write a program to simulate the process and display the result.

(Hint: Place the center of the square in the center of a coordinate system, as shown in (b). Randomly generate a point in the square and count the number of times a point falls into an odd-numbered region.)

2

3

1

4

(a)

2

3

1

4

(b)

4.45* (Math: combinations) Write a program that displays all possible combinations for picking two numbers from integers 1 to 7. Also display the total number of all combinations.

12

13

...

...

4.46* (Computer architecture: bit-level operations) A short value is stored in 16 bits. Write a program that prompts the user to enter a short integer and displays the 16 bits for the integer. Here are sample runs:

Enter an integer: 5

The bits are 0000000000000101

Enter an integer: -5

The bits are 1111111111111011

(Hint: You need to use the bitwise right shift operator (>>) and the bitwise AND operator (&), which are covered in Supplement III.D on the Companion Website.)

CHAPTER 5

METHODS

Objectives

To define methods (§5.2).

To invoke methods with a return value (§5.3).

To invoke methods without a return value (§5.4).

To pass arguments by value (§5.5).

To develop reusable code that is modular, easy to read, easy to debug, and easy to maintain (§5.6).

To write a method that converts decimals to hexadecimals (§5.7).

To use method overloading and understand ambiguous overloading (§5.8).

To determine the scope of variables (§5.9).

To solve mathematics problems using the methods in the Math class (§§5.10–5.11).

To apply the concept of method abstraction in software development (§5.12).

To design and implement methods using stepwise refinement (§5.12).

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]