Download presentation
Presentation is loading. Please wait.
1
Chapter 7 Repetition Statements
7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
2
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Chapter 7 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 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 ResponseBox class from the javabook package. Output formatted data using the Format class from the javabook package. (Optional) Write simple recursive methods. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
3
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 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. There are basically two types of terminating the loop: 1. count-controlled and 2. sentinel-controlled. Count-controlled loops terminate the execution of the loop after the loop body is executed for a fixed number of times. Sentinel-controlled loops terminate the execution of the loop after one of the designated values called a sentinel is encountered. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
4
Syntax for the while Statement
Chapter 7 Syntax for the while Statement while ( <boolean expression> ) <statement> Boolean Expression while ( number <= ) { sum = sum + number; number = number + 1; } Statement (loop body) 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
5
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Control Flow of while int sum = 0, number = 1 number <= 100 ? sum = sum + number; number = number + 1; true false 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
6
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 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; } 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
7
Example: Testing Input Data
Chapter 7 Example: Testing Input Data Here’s a realistic example of using the while loop to accept only the valid input data. Accepts age between 0 and 130, exclusively. Priming Read age = inputBox.getInteger("Your Age (between 0 and 130):"); while (age < 0 || age > 130) { messageBox.show("An invalid age was entered. " + "Please try again."); age = inputBox.getInteger( "Your Age (between 0 and 130):" ); } Things to Watch: There are two getInteger calls. Notice that the first one occurs outside of the loop because the age variable must have a value before the test in the boolean expression of the while statement. This reading of input values before the test is called priming read. Notice that the loop will continue as long as the input is invalid. The loop body of this while statement is executed zero times if the input is valid the first time. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
8
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 while 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 = 0; while ( count != 10 ) { count = count + 2; } 2 Note: In theory, this while statement is an infinite loop, but in programming languages other than Java, this loop will eventually terminate because of an overflow error. An overflow error will occur if you attempt to assign a value larger than the maximum value the variable can hold. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. With Java, however, an overflow will not cause the program termination. 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. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
9
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 while 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. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
10
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 while 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. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
11
Checklist for Repetition Control
Chapter 7 Checklist for Repetition Control 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. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
12
Useful Shorthand Operators
Chapter 7 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; 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); 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
13
The do-while Statement
Chapter 7 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. The following is the routine presented earlier that inputs a person’s age using the do–while statement. do { age = inputBox.getInteger("Your Age (between 0 and 130):"); if (age < 0 || age > 130) { messageBox.show("An invalid age was entered. " + "Please try again."); } } while (age < 0 || age > 130); This code is not as good as the version using the while statement it includes an if statement inside its loop body and the if test is repeating the same boolean expression of the do–while. Since the loop body is executed repeatedly, it is important not to include any extraneous statements. Moreover, duplicating the testing conditions tends to make the loop statement harder to understand. For this example, we can avoid the extra test inside the loop body and implement the control flow a little more clearly by using a while statement. In general, the while statement is more frequently used than the do–while statement. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
14
Syntax for the do-while Statement
Chapter 7 Syntax for the do-while Statement do <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= ); Statement (loop body) Boolean Expression 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
15
Control Flow of do-while
Chapter 7 Control Flow of do-while int sum = 0, number = 1 sum += number; number++; true sum <= ? false 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
16
Loop Control without Boolean Variable
Chapter 7 Loop Control without Boolean Variable sum = 0; do { num = inputBox.getInteger(); if (num == 0) //sentinel messageBox.show("Sum = " + sum); else if (num % 2 == 0) //invalid data messageBox.show("Error: even number was entered"); else { sum += num; if (sum > 1000) //pass the threshold messageBox.show("Sum became larger than 1000"); } } while ( !(num % 2 == 0 || num == 0 || sum > 1000) ); When you have multiple conditions to stop the loop and if you need to execute different responses to each of the multiple conditions, then the use of boolean variables often clarifies the meaning of the loop statement. The sample code on this slide computes the sum of odd integers entered by the user. The loop is terminated when the sentinel value 0 is entered, an even integer is entered, or the sum becomes larger than 1,000. The loop control shown on the slide does not use any boolean variable resulting in a structure where the boolean expression include duplicate tests. Because of the multiple conditions, the boolean expression gets much harder to read (and therefore, much easier to make mistakes). 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
17
Loop Control with Boolean Variable
Chapter 7 Loop Control with Boolean Variable boolean repeat = true; sum = 0; do { num = inputBox.getInteger(); if (num == 0) { //sentinel messageBox.show("Sum = " + sum); repeat = false; } else if (num % 2 == 0) { //invalid data messageBox.show("Error: even number was entered"); else { sum += num; if (sum > 1000) { //pass the threshold messageBox.show("Sum became larger than 1000"); } while ( repeat ); Terminates the loop by setting the boolean variable to false. The same routine now implemented with the use of boolean variable eliminates duplicate tests. The use of boolean variables is helpful in making loop statements readable, especially when the loop has multiple stop conditions. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
18
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 ResponseBox The ResponseBox class is used to get a YES or NO response from the user. MainWindow mainWindow = new MainWindow( ); ResponseBox yesNoBox = new ResponseBox( mainWindow ); yesNoBox.prompt( “Do you love Java?”); 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
19
ResponseBox – Processing the Selection
Chapter 7 ResponseBox – Processing the Selection To determine which button the user clicked, we write int selection = yesNoBox.prompt("Click a button"); switch (selection) { case ResponseBox.YES: messageBox.show("Yes button was clicked"); break; case ResponseBox.NO: messageBox.show("No button was clicked"); } 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
20
ResponseBox – Sample Usage
Chapter 7 ResponseBox – Sample Usage Here’s a typical use of ResponseBox: choice = yesNoBox.prompt ("Do you want to start the computation?"); while (choice == ResponseBox.YES) { //code for computation comes here ("Repeat another computation?"); } 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
21
ResponseBox – Other Usage
Chapter 7 ResponseBox – Other Usage ResponseBox can have up to three buttons with user- designated labels. ResponseBox threeButtonBox; threeButtonBox = new ResponseBox(mainWindow,3); threeButtonBox.setLabel( ResponseBox.BUTTON1, "OK" ); threeButtonBox.setLabel( ResponseBox.BUTTON2, "Cancel" ); threeButtonBox.setLabel( ResponseBox.BUTTON3, "Help" ); Processing can be done in the following manner: int selection = threeButtonBox.prompt("Click a button"); switch (selection) { case ResponseBox.BUTTON1: messageBox.show("Ok button was clicked"); break; case ResponseBox.BUTTON2: messageBox.show(“Cancel button was clicked"); break; case ResponseBox.BUTTON3: messageBox.show(“Help button was clicked"); } 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
22
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 ResponseBox Methods CLASS: ResponseBox Method Argument Description <constructor> MainWindow Creates a ResponseBox object. MainWindow, int Creates a ResponseBox object with N (the second argument) buttons, 1 <= N <= 3. If an invalid N is passed, then the object will include one button. prompt String Prompts the user with the text passed as an argument. Returns an integer that identifies the clicked button. See the explanation of the class constants. setLabel int, Sets the label of the designated button with the passed String. The first argument identifies the button. See the explanation of the class constants. Class Constant YES This value identifies the Yes button. NO This value identifies the No button. BUTTON1 This value identifies the leftmost button. The value of BUTTON1 is equal to the value of YES. BUTTON2 This value identifies the middle button. Note: the middle button becomes the rightmost button if there are only two buttons. The value of BUTTON2 is equal to the value of NO. BUTTON3 This value identifies the rightmost button when the ResponseBox includes three buttons. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
23
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 The for Statement int i, sum = 0, number; for (i = 0; i < 20; i++) { number = inputBox.getInteger(); sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, … , 19). 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
24
Syntax for the for Statement
Chapter 7 Syntax for the for Statement for ( <initialization>; <boolean expression>; <increment> ) <statement> Initialization Boolean Expression Increment for ( i = 0 ; i < ; i ) { number = inputBox.getInteger(); sum += number; } 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++) Statement (loop body) 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
25
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Control Flow of for i = 0; i < 20 ? false number = inputBox.getInteger( ); sum = number; true i ++; 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
26
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 More 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 Here’s another, much larger, example illustrating a for loop. double initialHeight, position, touchTime; MainWindow mainWindow = new MainWindow("Drop WaterMelon"); OutputBox outputBox = new OutputBox(mainWindow); InputBox inputBox = new InputBox(mainWindow); mainWindow.setVisible( true ); outputBox.setVisible( true ); initialHeight = inputBox.getDouble("Initial Height:"); touchTime = Math.sqrt(initialHeight / 16.0); outputBox.printLine(" Time t Position at Time t "); outputBox.skipLine(1); for (int time = 0; time < touchTime; time++) { position = * time*time + initialHeight; outputBox.print(" " + time); outputBox.printLine(" " + position); } //print the last second outputBox.printLine(" " + touchTime + " "); for (int k = 100; k > 0; k--) ) 3 k = 100, 99, 98, 97, ..., 1 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
27
The Nested-for Statement
Chapter 7 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. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
28
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Generating the Table int price; MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainWindow); mainWindow.setVisible( true ); outputBox.setTitle("Carpet Price Table"); outputBox.setVisible( true ); for (int width = 11; width <= 20; width++) { for (int length = 5; length <= 25; length += 5) { price = width * length * 19; //$19 per sq ft. outputBox.print(" " + price); } outputBox.skipLine(1); //skip a line after a row is finished INNER OUTER 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… 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
29
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Formatting Integers int x = 11, y = 22; outputBox.printLine( Format.leftAlign ( 10, x ) Format.leftAlign ( 10, y ) ); outputBox.printLine( Format.centerAlign( 10, x ) Format.centerAlign( 10, y ) ); outputBox.printLine( Format.rightAlign ( 10, x ) Format.rightAlign ( 10, y ) ); 10 The Format class from the javabook package provides convenience methods for formatting the output values. The basic idea of formatted output is to allocate the same amount of space for the output values and align the values within the allocated space. We call the space occupied by an output value the field and the number of characters allocated to a field its field width. leftAlign centerAlign rightAlign 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
30
Formatting Real Numbers
Chapter 7 Formatting Real Numbers double w = ; outputBox.printLine( Format.leftAlign ( 20, 2, w )); outputBox.printLine( Format.centerAlign( 20, 2, w )); outputBox.printLine( Format.rightAlign ( 20, 2, w )); 20 leftAlign centerAlign rightAlign Notice the decimal places are rounded when formatted. 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
31
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 Formatting Strings String s = “Java”; outputBox.printLine( Format.leftAlign ( 15, s )); outputBox.printLine( Format.centerAlign( 15, s )); outputBox.printLine( Format.rightAlign ( 15, s )); 15 leftAlign centerAlign rightAlign 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
32
Methods in The Format Class
Chapter 7 Methods in The Format Class 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
33
Sample Program: Hi-Lo Game
Chapter 7 Sample Program: Hi-Lo Game 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. Major Tasks do { Generate a secret number; Play one game; } while ( the user wants to play ); 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
34
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 HiLo – Design 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
35
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 HiLo – Object Diagram 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
36
HiLo Game – Development Steps
Chapter 7 HiLo Game – Development Steps Start with a program skeleton. Define the HiLoMain and HiLo classes. Add code to the HiLo class to play a game using a dummy secret number. Add code to the HiLo class to generate a random number. Finalize the code by removing temporary statements and tying up loose ends. The End 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
37
Let's Try an Exercise (#4)
Get the following integers from a user: A starting number A stopping number A increment number Vertically output the results in an OutputBox 7/10/2019 Introduction to Object-Oriented Programming with Java--Wu
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.