Download presentation
Presentation is loading. Please wait.
1
Intro to OOP with Java, C. Thomas Wu
Chapter 6 Repetition Statements (powerpoint slides from the publisher, tantc, and leeml) Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
2
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program using while statements. Implement repetition control in a program using do-while statements. Implement a generic loop-and-a-half repetition control statement Implement repetition control in a program using for statements. Nest a loop repetition statement inside another repetition statement. Choose the appropriate repetition control statement for a given task Prompt the user for a yes-no reply using the showConfirmDialog method of JOptionPane. (Optional) Write simple recursive methods We will study two forms of repetition statements in this lesson. They are while and do-while statement. ©The McGraw-Hill Companies, Inc.
3
Intro to OOP with Java, C. Thomas Wu
Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered. Repetition statements are called loop statements also. In Chapter 5, we studied selection control statements. We will study in this chapter the second type of control statement, a repetition statement, that alters the sequential control flow. It controls the number of times a block of code is executed. In other words, a block of code is executed repeatedly until some condition occurs to stop the repetition. There are fundamentally two ways to stop the repetition—count-controlled and sentinel-controlled. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
4
Intro to OOP with Java, C. Thomas Wu II. while Statement
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
5
Intro to OOP with Java, C. Thomas Wu
The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100. The first repetition control we will study is the while statement. Here’s an example that computes the sum of integers from 1 to 100, inclusively. Note: there’s a closed form to compute the sum of 1 to 100, which is (100 * 101) / 2, so this repetition statement is a illustration purpose only. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
6
Syntax for the while Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the while Statement while ( <boolean expression> ) <statement> Boolean Expression while ( number <= ) { sum = sum + number; number = number + 1; } Statement (loop body) Here’s the general syntax of a while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body may not be executed at all. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
7
Intro to OOP with Java, C. Thomas Wu
Control Flow of while int sum = 0, number = 1 number <= 100 ? sum = sum + number; number = number + 1; true false This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
8
Intro to OOP with Java, C. Thomas Wu
More Examples int sum = 0, number = 1; while ( sum <= ) { sum = sum + number; number = number + 1; } 1 Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while (number <= lastNumber) { product = product * number; number = number + 2; } 2 Computes the product of the first 20 odd integers. Variation on computing the product of the first 20 odd integers: int product = 1, number = 1, lastTerm = 20, count = 1; while ( count <= lastTerm ) { product = product * (2 * number – 1); count = count + 1; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
9
Example: Testing Input Data
Intro to OOP with Java, C. Thomas Wu Example: Testing Input Data String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); while (age < 0 || age > 130) { JOptionPane.showMessageDialog(null, "An invalid age was entered. Please try again."); age = Integer.parseInt(inputStr); } Priming Read Here's a more practical example of using a repetition statement. This code will only accept a value greater than 0 but less than 130. If an input value is invalid, then the code will repeat until the valid input is read. Notice that the 'age' variable must have a value before the boolean expression of the while statement can be evaluated. We therefore read the input value before the while test. This reading of input values before the test is called priming read. The loop body of this while statement is executed zero times if the input is valid the first time. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
10
Useful Shorthand Operators
Intro to OOP with Java, C. Thomas Wu Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to Operator Usage Meaning += a += b; a = a + b; -= a -= b; a = a – b; *= a *= b; a = a * b; /= a /= b; a = a / b; %= a %= b; a = a % b; When writing a repetition statement, we often see the statement that modifies the value of a variable in the form such as sum = sum + number. Because of a high occurrence of such statement, we can use shorthand operators. These shorthand assignment operators have precedence lower than any other arithmetic operators, so, for example, the statement sum *= a + b; is equivalent to sum = sum * (a + b); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
11
Intro to OOP with Java, C. Thomas Wu
Confirmation Dialog A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, /*prompt*/ "Play Another Game?", /*dialog title*/ "Confirmation", /*button options*/ JOptionPane.YES_NO_OPTION); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
12
Example: Confirmation Dialog
Intro to OOP with Java, C. Thomas Wu Example: Confirmation Dialog boolean keepPlaying = true; int selection; while (keepPlaying){ //code to play one game comes here // . . . selection = JOptionPane.showConfirmDialog(null, "Play Another Game?", "Confirmation", JOptionPane.YES_NO_OPTION); keepPlaying = (selection == JOptionPane.YES_OPTION); } Here's an example of how we can use a confirmation dialog in a loop. At the end of the loop, we prompt the user to repeat the loop again or not. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
13
Intro to OOP with Java, C. Thomas Wu
Watch Out for Pitfalls Watch out for the off-by-one error (OBOE). Make sure the loop body contains a statement that will eventually cause the loop to terminate. Make sure the loop repeats exactly the correct number of times. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
14
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 1 int product = 0; while ( product < ) { product = product * 5; } 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 If you are not careful, you can easily end up writing an infinite loop. Make sure the test is written in such a way that the loop will terminate eventually. ©The McGraw-Hill Companies, Inc.
15
Intro to OOP with Java, C. Thomas Wu
Overflow An infinite loop often results in an overflow error. An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
16
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 2 float count = 0.0f; while ( count != 1.0f ) { count = count f; } //seven 3s 1 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count != 1.0f ) { count = count f; } //eight 3s 2 Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/ / /3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
17
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall – 2a int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result); 1 Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. 10 11 int result = 0; double cnt = 0.0; while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result); 2 Here's another example of using a double variable as a counter. The two loops are identical in concept, and therefore, should output the same result. They would if real numbers are stored precisely in computer memory. Because the value of 0.1 cannot be represented precisely in computer memory, the second one will actually print out 11, while the first one prints out 10, as expected. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
18
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while ( count < 10 ){ . . . count++; } 1 count = 1; while ( count <= 10 ){ . . . count++; } 2 count = 0; while ( count <= 10 ){ . . . count++; } 3 count = 0; while ( count < 10 ){ . . . count++; } 4 Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop. 1 3 and exhibit off-by-one error. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
19
Loop-and-a-Half Repetition Control
Intro to OOP with Java, C. Thomas Wu Loop-and-a-Half Repetition Control Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body. It is implemented by using reserved words while, if, and break. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
20
Example: Loop-and-a-Half Control
Intro to OOP with Java, C. Thomas Wu Example: Loop-and-a-Half Control String name; while (true){ name = JOptionPane.showInputDialog(null, "Your name"); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, "Invalid Entry." + "You must enter at least one character."); } This is a simple example of a loop-and-a-half control. Notice the priming read is avoided with this control. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
21
Pitfalls for Loop-and-a-Half Control
Intro to OOP with Java, C. Thomas Wu Pitfalls for Loop-and-a-Half Control Be aware of two concerns when using the loop-and-a-half control: The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop. Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
22
Loop: break Statement (1/4)
int i = 1; int sum = 0; while (sum < 20) { sum += i; ++i; } System.out.println("sum is " + sum); System.out.println("i is " + i); sum is 21 i is 7 int i = 1; int sum = 0; while (sum < 20) { sum += i; if (sum % 2 == 0) break; ++i; } System.out.println("sum is " + sum); System.out.println("i is " + i); sum is 6 i is 3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
23
Loop: break Statement (2/4)
int i = 1; int sum = 0; while ( true ) { sum += i; if (sum > 10) break; ++i; } System.out.println("sum is " + sum); System.out.println("i is " + i); sum is 15 i is 5 Note: Without the break, this is an infinite loop! int i = 0; int sum = 0; while (sum <= 10) { ++i; sum += i; } System.out.println("sum is " + sum); System.out.println("i is " + i); Try to avoid using break, unless very necessary. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
24
Loop: break Statement (3/4)
Random number = new Random(); int i; while (true) { i = number.nextInt(100); System.out.println("i is " + i); if (i >= 80) break; } i is 43 i is 2 i is 12 i is 95 Random class will be discussed later. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
25
Loop: break Statement (4/4)
break causes control to get out of the inner-most loop that contains it. int a = 1; while (a < 5) { int b = 1; while (b < 5) { System.out.println("a is " + a + ", b is " + b); if (b == 2) break; ++b; } ++a; a is 1, b is 1 a is 1, b is 2 a is 2, b is 1 a is 2, b is 2 a is 3, b is 1 a is 3, b is 2 a is 4, b is 1 a is 4, b is 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
26
Loop: continue Statement (1/2)
Sometimes we may want to immediately go to the next iteration, without executing the rest of the statements in the body of the loop. This can be done using continue. Like break, continue only causes control to go to the next iteration of the inner-most loop that contains it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
27
Loop: continue Statement (2/2)
i is 1 i is 2 i is 4 i is 5 i is 6 i is 7 int i = 0; while (i <= 6) { ++i; if (i == 3) continue; System.out.println("i is " + i); } int i = 1; int sum = 0; while (sum < 20) { sum += i; if (sum % 2 == 0) continue; ++i; } System.out.println("sum is " + sum); System.out.println("i is " + i); sum is 23 i is 6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
28
Intro to OOP with Java, C. Thomas Wu III. do while Statement
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
29
The do-while Statement
Intro to OOP with Java, C. Thomas Wu The do-while Statement int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= ); These statements are executed as long as sum is less than or equal to 1,000,000. Here's an example of the second type of repetition statement called do-while. This sample code computes the sum of integers starting from 1 until the sum becomes greater than 1,000,000. The main difference between the while and do-while is the relative placement of the test. The test occurs before the loop body for the while statement, and the text occurs after the loop body for the do-while statement. Because of this characteristic, the loop body of a while statement is executed 0 or more times, while the loop body of the do-while statement is executed 1 or more times. In general, the while statement is more frequently used than the do–while statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
30
Syntax for the do-while Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the do-while Statement do <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= ); Statement (loop body) Boolean Expression Here’s the general syntax of a do-while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body is executed at least once. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
31
Control Flow of do-while
int sum = 0, number = 1 sum += number; number++; true sum <= ? false ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
32
Intro to OOP with Java, C. Thomas Wu IV. for Statement
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
33
Intro to OOP with Java, C. Thomas Wu
The for Statement int i, sum = 0, number; for (i = 0; i < 20; i++) { number = scanner.nextInt( ); sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, … , 19). This is a basic example of a for statement. This for statement reads 20 integers and compute their sum. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
34
Syntax for the for Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the for Statement for ( i = 0 ; i < ; i ) { number = scanner.nextInt(); sum += number; } for ( <initialization>; <boolean expression>; <increment> ) <statement> Initialization Boolean Expression Increment Statement (loop body) This shows the general syntax for the for statement. The <initialization> component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i < 10; i++) instead of int i; for (i = 0; i < 10; i++) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
35
Intro to OOP with Java, C. Thomas Wu
Control Flow of for i = 0; i < 20 ? false number = ; sum = number; true i ++; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
36
Intro to OOP with Java, C. Thomas Wu
More for Loop Examples for (int i = 0; i < 100; i += 5) 1 i = 0, 5, 10, … , 95 for (int j = 2; j < 40; j *= 2) 2 j = 2, 4, 8, 16, 32 for (int k = 100; k > 0; k--) ) 3 Here are some more examples of a for loop. Notice how the counting can go up or down by changing the increment expression accordingly. k = 100, 99, 98, 97, ..., 1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
37
i++ or ++i? Any difference? for ( i = 0; i < 20; i++ ) { ... }
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
38
Index Variable Scope Consider: int currentTerm = 2; for (int i = 0; i < 5; ++i) { System.out.println(CurrentTerm); CurrentTerm *= 2; } System.out.println("i is " + i); Does not compile, because the scope of the index variable i is limited to the for loop. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
39
Intro to OOP with Java, C. Thomas Wu V. Nested Repetition Statements
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
40
The Nested-for Statement
Intro to OOP with Java, C. Thomas Wu The Nested-for Statement Nesting a for statement inside another for statement is commonly used technique in programming. Let’s generate the following table using nested-for statement. Just an if statement can be nested inside another if statement, we often nest for loops. For example, using a nest-for loop is the most appropriate way to generate a table such as the illustration. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
41
Intro to OOP with Java, C. Thomas Wu
Generating the Table int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19 per sq. ft. System.out.print (" " + price); } //finished one row; move on to next row System.out.println(""); OUTER INNER Here's how the table can be produced by a nested-for loop. For each value of width, length will range from 5 to 25 with an increment of 5. Here’s how the values for width and length change over the course of execution. width length 11 5 10 15 20 25 12 13 and so on… ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
42
Nested-for Loops (1/2) i is 0 j is 0 j is 1 j is 2 j is 3 i is 1
for (int i = 0; i < 3; ++i) { System.out.println("i is " + i); for (int j = 0; j < 4; ++j) { System.out.println(" j is " + j); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
43
Nested-for Loops (2/2) What is the output?
for (int i = 0; i < 3; ++i) { System.out.println("i is " + i); for (int j = 0; j < i; ++j) { System.out.println(" j is " + j); } What is the output? ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
44
break and continue in for statement
The break and continue statements work the same way in a for loop as in a while loop. i is 0 j is 0 j is 1 i is 1 i is 2 for (int i = 0; i < 3; ++i) { System.out.println("i is " + i); for (int j = 0; j < 4; ++j) { if (j == 2) break; System.out.println(" j is " + j); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
45
Intro to OOP with Java, C. Thomas Wu VI. Useful Classes
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
46
Random Numbers (1/2) Random number generation is discussed in section 3.8 of your textbook. We learn another way here, using the Random class. Notes: Need to import java.util.*; Random( ): constructs a new random number generator Random whose seed is based on the current time. int nextInt(int n): returns the next pseudo-random, from the interval [0, 1, … n-1], uniformly distributed value of a Random object. Refer to the API specification for the complete description of class Random. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
47
Random Numbers (2/2) import java.util.*; public class Random1 {
public static void main(String[] args) { Random num = new Random(); for (int i=0; i<5; i++) { System.out.println("Next random number is " + num.nextInt(100)); } Next random number is 48 Next random number is 14 Next random number is 89 Next random number is 7 Next random number is 44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
48
Intro to OOP with Java, C. Thomas Wu
Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6. From Java 5.0, we can use the Formatter class. System.out (PrintStream) also includes the format method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
49
Intro to OOP with Java, C. Thomas Wu
The Formatter Class We use the Formatter class to format the output. First we create an instance of the class Formatter formatter = new Formatter(System.out); Then we call its format method int num = 467; formatter.format("%6d", num); This will output the value with the field width of 6. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
50
The format Method of Formatter
Intro to OOP with Java, C. Thomas Wu The format Method of Formatter The general syntax is format(<control string>, <expr1>, <expr2>, ) Example: int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
51
The format Method of PrintStream
Intro to OOP with Java, C. Thomas Wu The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format("%6d", 498); is equivalent to System.out.format("%6d", 498); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
52
Intro to OOP with Java, C. Thomas Wu
Control Strings Integers % <field width> d Real Numbers % <field width> . <decimal places> f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
53
Intro to OOP with Java, C. Thomas Wu
VII. Computational Time Consideration Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
54
Estimating the Execution Time
Intro to OOP with Java, C. Thomas Wu Estimating the Execution Time In many situations, we would like to know how long it took to execute a piece of code. For example, Execution time of a loop statement that finds the greatest common divisor of two very large numbers, or Execution time of a loop statement to display all prime numbers between 1 and 100 million Execution time can be measured easily by using the Date class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
55
Intro to OOP with Java, C. Thomas Wu
Using the Date Class Here's one way to measure the execution time Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime(); We can achieve the same result by using the currentTimeMillis method of the System class as long start = System.currentTimeMillis(); //code to measure long end = System.currentTimeMillis(); long elapsedTimeInMilliSec = end – start; To get the elasped time in seconds, we divide the milliseconds by 1000 long elapsedTimeInSec = elapsedTimeInMilliSec / 1000; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
56
Intro to OOP with Java, C. Thomas Wu
Finding GCD If we want to reduce a fraction to its simplest form, we need to find the greatest common divisor (GCD) of its numerator and denominator. Method 1 – Brute force. Given two positive integers M and N, we find their GCD by dividing M and N with values from 1 to M. The last integer that divided both M and N perfectly (no remainder) is the GCD. Finally, let us look at a slight more complicated example. In order to reduce a fraction o its simplest form, we need to find the GCD of its numerator and denominator. We define a method that returns the GCD of two given arguments. We will develop the full definition of the Fraction class later. Two solutions: The brute force solution applies the definition of GCD directly. Given two positive integers M and N, we find their GCD by dividing M and N with values from 1 to M. The last integer that divided both M and N perfectly (no remainder) is the GCD. For example, 24 and 36. The numbers that divide 24 and 36 perfectly are 1, 2, 3, 4, 6, and 12. So the GCD is 12. The fraction 24/36 is reduced to the simplest form 2/3 by dividing 24 and 36 by 12. Use the modulo arithmetic operator. A more elegant solution is based on the Euclidean algo. Given 44 and 16, first divie 44 by 16. The remainder is 12. We have the relation 44 = 2* Conclude that the GCD that divides 44 and 16 must also divide 12. Otherwise, we get a contradiction. So we reduce the problem of finding GCD(44,16) to GCD(16,12). Repeat the process 16 = 1* Reduce the problem to GCD(16,4). Since 12 = 3*4 + 0 gives no remainder, we finish the process and return 4 as the GCD. Sequence of reduction is GCD(44,16) = GCD(16,12) = GCD(12,4) = 4. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
57
Intro to OOP with Java, C. Thomas Wu
Finding GCD Method 2 – Euclidean Algorithm. Given two positive integers M and N, we divide M by N to get the remainder R. We have the relation M = N*Q + R. GCD that divides M and N must also divide R. Reduce the problem of finding GCD (M,N) to finding GCD (N, R). Repeat process until R=0. Return N as the GCD. Finally, let us look at a slight more complicated example. In order to reduce a fraction o its simplest form, we need to find the GCD of its numerator and denominator. We define a method that returns the GCD of two given arguments. We will develop the full definition of the Fraction class later. Two solutions: The brute force solution applies the definition of GCD directly. Given two positive integers M and N, we find their GCD by dividing M and N with values from 1 to M. The last integer that divided both M and N perfectly (no remainder) is the GCD. For example, 24 and 36. The numbers that divide 24 and 36 perfectly are 1, 2, 3, 4, 6, and 12. So the GCD is 12. The fraction 24/36 is reduced to the simplest form 2/3 by dividing 24 and 36 by 12. Use the modulo arithmetic operator. A more elegant solution is based on the Euclidean algo. Given 44 and 16, first divie 44 by 16. The remainder is 12. We have the relation 44 = 2* Conclude that the GCD that divides 44 and 16 must also divide 12. Otherwise, we get a contradiction. So we reduce the problem of finding GCD(44,16) to GCD(16,12). Repeat the process 16 = 1* Reduce the problem to GCD(16,4). Since 12 = 3*4 + 0 gives no remainder, we finish the process and return 4 as the GCD. Sequence of reduction is GCD(44,16) = GCD(16,12) = GCD(12,4) = 4. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
58
Intro to OOP with Java, C. Thomas Wu
Finding GCD Example N M R=N%M GCD(44,16) 44 % 16 = 12 GCD(16,12) 16 % 12 = 4 GCD(12, 4) 12 % 4 = 0 Finally, let us look at a slight more complicated example. In order to reduce a fraction o its simplest form, we need to find the GCD of its numerator and denominator. We define a method that returns the GCD of two given arguments. We will develop the full definition of the Fraction class later. Two solutions: The brute force solution applies the definition of GCD directly. Given two positive integers M and N, we find their GCD by dividing M and N with values from 1 to M. The last integer that divided both M and N perfectly (no remainder) is the GCD. For example, 24 and 36. The numbers that divide 24 and 36 perfectly are 1, 2, 3, 4, 6, and 12. So the GCD is 12. The fraction 24/36 is reduced to the simplest form 2/3 by dividing 24 and 36 by 12. Use the modulo arithmetic operator. A more elegant solution is based on the Euclidean algo. Given 44 and 16, first divie 44 by 16. The remainder is 12. We have the relation 44 = 2* Conclude that the GCD that divides 44 and 16 must also divide 12. Otherwise, we get a contradiction. So we reduce the problem of finding GCD(44,16) to GCD(16,12). Repeat the process 16 = 1* Reduce the problem to GCD(16,4). Since 12 = 3*4 + 0 gives no remainder, we finish the process and return 4 as the GCD. Sequence of reduction is GCD(44,16) = GCD(16,12) = GCD(12,4) = 4. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
59
Finding GCD Direct Approach More Efficient Approach
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
60
Intro to OOP with Java, C. Thomas Wu VIII. Sample Development
Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
61
Intro to OOP with Java, C. Thomas Wu
Problem Statement Write an application that will play Hi-Lo games with the user. The objective of the game is for the user to guess the computer-generated secret number in the least number of tries. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number. The maximum number of tries allowed for each game is six. The user can play as many games as she wants. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
62
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: do { Task 1: generate a secret number; Task 2: play one game; } while ( the user wants to play ); As a part of the overall plan, we begin by identifying the main tasks for the program. Unlike the overall plan for the previous sample developments, we will use a pseudo code to express the top level logic of the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
63
Intro to OOP with Java, C. Thomas Wu
Required Classes JOptionPane Math standard classes Ch6HiLo main class The structure of this program is very simple. We will use two standard classes, one for input and output and another for generating random numbers. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
64
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in four steps: Start with a skeleton Ch6HiLo class. Add code to the Ch6HiLo class to play a game using a dummy secret number. Add code to the Ch6HiLo class to generate a random number. Finalize the code by tying up loose ends. The second and the third steps correspond to the two major tasks identified in the overall plan. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
65
Intro to OOP with Java, C. Thomas Wu
Step 1 Design The topmost control logic of HiLo 1. describe the game rules; 2. prompt the user to play a game or not; while ( answer is yes ) { 3. generate the secret number; 4. play one game; 5. prompt the user to play another game or not; } In the first step, we determine a little more detailed control logic than the one stated in the overall plan. For each of the five identified functions, we will define a method: describeRules, generateSecretNumber, playGame, and prompt. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
66
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter6/Step1 Source Files: Ch6HiLo.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
67
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program and verify confirm that the topmost control loop terminates correctly under different conditions. Play the game zero times one time one or more times Run the program and verify that the topmost control loop is functioning correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
68
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Implement the playGame method that plays one game of HiLo. Use a dummy secret number By using a fix number such as 45 as a dummy secret number, we will be able to test the correctness of the playGame method In order to verify whether our code is working correctly or not, we need to know what is the secret number. The easiest way to do this is to use a fixed number, such as 45, make the temporary generateRandomNumber to return this fixed number. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
69
Intro to OOP with Java, C. Thomas Wu
The Logic of playGame int guessCount = 0; do { get next guess; guessCount++; if (guess < secretNumber) { print the hint LO; } else if (guess > secretNumber) { print the hint HI; } } while (guessCount < number of guesses allowed && guess != secretNumber ); if (guess == secretNumber) { print the winning message; } else { print the losing message; Here's the playGame method expressed as a pseudocode. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
70
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter6/Step2 Source Files: Ch6HiLo.java We implement the playGame and getNextGuess methods in this step. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
71
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We compile and run the program numerous times To test getNextGuess, enter a number less than 1 a number greater than 100 a number between 2 and 99 the number 1 and the number 100 To test playGame, enter a guess less than 45 a guess greater than 45 45 six wrong guesses We need to verify the correctness of two methods: playGame and getNextGuess. Try all cases presented here and confirm that you get the expected responses. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
72
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We complete the generateSecretNumber method. We want to generate a number between 1 and 100 inclusively. private void generateSecretNumber( ) { double X = Math.random(); secretNumber = (int) Math.floor( X * 100 ) + 1; System.out.println("Secret Number: " secretNumber); // TEMP return secretNumber; } Notice that we have one temporary statement to output the value of secretNumber. We include it for the testing purpose, i.e., we need to check the numbers generated are valid. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
73
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter6/Step3 Source Files: Ch6HiLo.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
74
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We use a separate test driver to generate 1000 secret numbers. We run the program numerous times with different input values and check the results. Try both valid and invalid input values and confirm the response is appropriate As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count < N && 1 <= number && number <= 100 ); if ( number < 1 || number > 100 ) { System.out.println("Error: " + number); } else { System.out.println("Okay"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
75
Intro to OOP with Java, C. Thomas Wu
Step 4: Finalize Program Completion Finish the describeRules method Remove all temporary statements Possible Extensions Allow the user to set her desired min and max for secret numbers Allow the user to set the number of guesses allowed Keep the score—the number of guesses made —while playing games and display the average score when the user quits the program ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.