Chapter 7
Repetition Statements
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 1
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.
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 2
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.
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 3
Syntax for the while Statement
while ( <boolean expression> )
<statement>
Boolean Expression
while (
sum
Statement
(loop body)
number <= 100
=
) {
sum + number;
number = number + 1;
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 4
Control Flow of while
int sum = 0, number = 1
number <=
100 ?
false
true
sum = sum + number;
number = number + 1;
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 5
More Examples
1
int sum = 0, number = 1;
while ( sum <= 1000000 ) {
sum
=
sum + number;
Keeps adding the
numbers 1, 2, 3, … until
the sum becomes larger
than 1,000,000.
number = number + 1;
}
2
int product = 1, number = 1,
count
= 20, lastNumber;
Computes the product of
the first 20 odd integers.
lastNumber = 2 * count - 1;
while (number <= lastNumber) {
product = product * number;
number
= number + 2;
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 6
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):" );
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 7
while Loop Pitfall - 1
1
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
Infinite Loops
2
int count = 0;
Both loops will not
terminate because the
boolean expressions will
never become false.
while ( count != 10 ) {
count = count + 2;
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 8
while Loop Pitfall - 2
1
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
}
//seven 3s
Using Real Numbers
2
float count = 0.0f;
Loop 2 terminates, but Loop
1 does not because only an
approximation of a real
number can be stored in a
computer memory.
while ( count != 1.0f ) {
count = count + 0.33333333f;
}
10/3/2015
//eight 3s
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 9
while Loop Pitfall - 3
Goal: Execute the loop body 10 times.
1
2
count = 1;
while ( count < 10 )
{
while ( count <= 10 )
{
. . .
. . .
count++;
count++;
}
3
}
4
count = 0;
while ( count <= 10 )
{
}
count = 1;
count = 0;
while ( count < 10 )
{
. . .
. . .
count++;
count++;
}
1 and 3 exhibit off-by-one error.
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 10
Checklist for Repetition Control
1. Watch out for the off-by-one error (OBOE).
2. Make sure the loop body contains a statement that
will eventually cause the loop to terminate.
3. Make sure the loop repeats exactly the correct
number of times.
4. 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.
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 11
Useful Shorthand Operators
sum = sum + number;
10/3/2015
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;
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 12
The do-while Statement
int sum = 0, number = 1;
do {
sum += number;
number++;
These statements are
executed as long as sum
is less than or equal to
1,000,000.
} while ( sum <= 1000000 );
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 13
Syntax for the do-while Statement
do
<statement>
while ( <boolean expression> ) ;
do
{
sum += number;
Statement
(loop body)
number++;
}
while (
sum <= 1000000
);
Boolean Expression
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 14
Control Flow of do-while
int sum = 0, number = 1
sum += number;
number++;
sum <=
1000000 ?
true
false
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 15
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) );
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 16
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)
Terminates the
loop by setting
the boolean
variable to false.
{
//invalid data
messageBox.show("Error: even number was entered");
repeat = false;
}
else {
sum += num;
if (sum > 1000) {
//pass the threshold
messageBox.show("Sum became larger than 1000");
repeat = false;
}
}
} while ( repeat );
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 17
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?”);
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 18
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");
break;
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 19
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
choice = yesNoBox.prompt
("Repeat another computation?");
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 20
ResponseBox – Other Usage
ResponseBox can have up to three buttons with userdesignated labels.
ResponseBox
threeButtonBox;
threeButtonBox = new ResponseBox(mainWindow,3);
threeButtonBox.setLabel( ResponseBox.BUTTON1, "OK"
);
threeButtonBox.setLabel( ResponseBox.BUTTON2, "Cancel" );
threeButtonBox.setLabel( ResponseBox.BUTTON3, "Help"
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
);
Chapter 7 - 21
ResponseBox Methods
CLASS:
Method
<constructor>
<constructor>
prompt
setLabel
ResponseBox
Argument
Description
MainWindow
Creates a ResponseBox object.
MainWindow,
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.
int
String
int,
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.
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
Description
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.
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 22
The for Statement
int i, sum = 0, number;
for (i = 0; i < 20; i++) {
number = inputBox.getInteger();
sum += number;
}
10/3/2015
These statements are
executed for 20 times
( i = 0, 1, 2, … , 19).
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 23
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment>
<statement>
Boolean
Expression
Initialization
for (
i = 0
;
i < 20
Increment
;
number = inputBox.getInteger();
sum += number;
i++
) {
Statement
(loop body)
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 24
)
Control Flow of for
i = 0;
false
i < 20 ?
true
number =
inputBox.getInteger( );
sum
+= number;
i ++;
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 25
More Examples
1
for (int i = 0; i < 100; i += 5)
i = 0, 5, 10, … , 95
2
for (int j = 2; j < 40; j *= 2)
j = 2, 4, 8, 16, 32
3
for (int k = 100; k > 0; k--) )
k = 100, 99, 98, 97, ..., 1
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 26
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.
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 27
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++) {
INNER
OUTER
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
}
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 28
Formatting Integers
int x = 11, y = 22;
outputBox.printLine( Format.leftAlign
Format.leftAlign
( 10, x ) +
( 10, y ) );
outputBox.printLine( Format.centerAlign( 10, x ) +
Format.centerAlign( 10, y ) );
outputBox.printLine( Format.rightAlign ( 10, x ) +
Format.rightAlign ( 10, y ) );
leftAlign
centerAlign
rightAlign
10
10/3/2015
10
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 29
Formatting Real Numbers
double w = 1234.5678;
outputBox.printLine( Format.leftAlign
( 20, 2, w ));
outputBox.printLine( Format.centerAlign( 20, 2, w ));
outputBox.printLine( Format.rightAlign ( 20, 2, w ));
leftAlign
centerAlign
rightAlign
20
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 30
Formatting Strings
String s = “Java”;
outputBox.printLine( Format.leftAlign
( 15, s ));
outputBox.printLine( Format.centerAlign( 15, s ));
outputBox.printLine( Format.rightAlign ( 15, s ));
leftAlign
centerAlign
rightAlign
15
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 31
Methods in The Format Class
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 32
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 computergenerated 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 {
1. Generate a secret number;
2. Play one game;
} while ( the user wants to play );
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 33
HiLo – Design
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 34
HiLo – Object Diagram
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 35
HiLo Game – Development Steps
1. Start with a program skeleton. Define the HiLoMain and
HiLo classes.
2. Add code to the HiLo class to play a game using a
dummy secret number.
3. Add code to the HiLo class to generate a random
number.
4. Finalize the code by removing temporary statements
and tying up loose ends.
The End
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 36
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
10/3/2015
Introduction to Object-Oriented Programming with Java--Wu
Chapter 7 - 37
Descargar

Sample Title Comes Here - Western Michigan University