? 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 1
Chapter 7
Repetition Statements
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 2
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 3
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 4
while ( number <= 100 ) {
sum = sum + number;
number = number + 1;
}
Syntax for the while Statement
while ( <boolean expression> )
<statement>
Statement
(loop body)
Boolean Expression
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 5
Control Flow of while
int sum = 0,number = 1
number <=
100?
false
sum = sum + number;
number = number + 1;
true
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 6
More Examples
Keeps adding the
numbers 1,2,3,… until
the sum becomes larger
than 1,000,000.
Computes the product of
the first 20 odd integers.
int sum = 0,number = 1;
while ( sum <= 1000000 ) {
sum = sum + number;
number = number + 1;
}
1
int product = 1,number = 1,
count = 20,lastNumber;
lastNumber = 2 * count - 1;
while (number <= lastNumber) {
product = product * number;
number = number + 2;
}
2
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 7
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):" );
}
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
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 8
while Loop Pitfall - 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
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 9
while Loop Pitfall - 2
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 + 0.33333333f;
} //eight 3s
2
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
} //seven 3s
1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 10
while Loop Pitfall - 3
Goal,Execute the loop body 10 times.
count = 1;
while ( count < 10 )
{
.,,
count++;
}
1
count = 0;
while ( count <= 10 )
{
.,,
count++;
}
3
count = 1;
while ( count <= 10 )
{
.,,
count++;
}
2
count = 0;
while ( count < 10 )
{
.,,
count++;
}
4
1 3and exhibit off-by-one error.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 11
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 12
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;
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 13
The do-while Statement
int sum = 0,number = 1;
do {
sum += number;
number++;
} while ( sum <= 1000000 );
These statements are
executed as long as sum
is less than or equal to
1,000,000.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 14
do {
sum += number;
number++;
} while ( sum <= 1000000 );
Syntax for the do-while Statement
do
<statement>
while ( <boolean expression> ) ;
Statement
(loop body)
Boolean Expression
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 15
Control Flow of do-while
int sum = 0,number = 1
sum += number;
number++;
sum <=
1000000?
true
false
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 16
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) );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 17
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");
repeat = false;
}
else {
sum += num;
if (sum > 1000) { //pass the threshold
messageBox.show("Sum became larger than 1000");
repeat = false;
}
}
} while ( repeat );
Terminates the
loop by setting
the boolean
variable to false.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 18
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?”);
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 19
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;
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 20
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?");
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 21
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" );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 22
ResponseBox Methods
CLASS,ResponseBox
Method Argument Description
<constructor> MainWindow Creates a ResponseBox object.
<constructor>
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,
String
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 23
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 ).
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 24
for ( i = 0 ; i < 20 ; i++ ) {
number = inputBox.getInteger();
sum += number;
}
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Initialization Boolean Expression Increment
Statement
(loop body)
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 25
Control Flow of for
i = 0;
false
number =
inputBox.getInteger( );
sum += number;
true
i ++;
i < 20?
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 26
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
for (int k = 100; k > 0; k--) )3
k = 100,99,98,97,...,1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 27
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,
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 28
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
}
INNE
R
OU
TE
R
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 29
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 10
leftAlign
centerAlign
rightAlign
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 30
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 ));
20
leftAlign
centerAlign
rightAlign
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 31
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
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 32
Methods in The Format Class
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 33
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 {
1,Generate a secret number;
2,Play one game;
} while ( the user wants to play );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 34
HiLo – Design
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 35
HiLo – Object Diagram
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 36
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
Chapter 7
Repetition Statements
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 2
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 3
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 4
while ( number <= 100 ) {
sum = sum + number;
number = number + 1;
}
Syntax for the while Statement
while ( <boolean expression> )
<statement>
Statement
(loop body)
Boolean Expression
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 5
Control Flow of while
int sum = 0,number = 1
number <=
100?
false
sum = sum + number;
number = number + 1;
true
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 6
More Examples
Keeps adding the
numbers 1,2,3,… until
the sum becomes larger
than 1,000,000.
Computes the product of
the first 20 odd integers.
int sum = 0,number = 1;
while ( sum <= 1000000 ) {
sum = sum + number;
number = number + 1;
}
1
int product = 1,number = 1,
count = 20,lastNumber;
lastNumber = 2 * count - 1;
while (number <= lastNumber) {
product = product * number;
number = number + 2;
}
2
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 7
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):" );
}
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
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 8
while Loop Pitfall - 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
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 9
while Loop Pitfall - 2
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 + 0.33333333f;
} //eight 3s
2
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
} //seven 3s
1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 10
while Loop Pitfall - 3
Goal,Execute the loop body 10 times.
count = 1;
while ( count < 10 )
{
.,,
count++;
}
1
count = 0;
while ( count <= 10 )
{
.,,
count++;
}
3
count = 1;
while ( count <= 10 )
{
.,,
count++;
}
2
count = 0;
while ( count < 10 )
{
.,,
count++;
}
4
1 3and exhibit off-by-one error.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 11
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 12
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;
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 13
The do-while Statement
int sum = 0,number = 1;
do {
sum += number;
number++;
} while ( sum <= 1000000 );
These statements are
executed as long as sum
is less than or equal to
1,000,000.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 14
do {
sum += number;
number++;
} while ( sum <= 1000000 );
Syntax for the do-while Statement
do
<statement>
while ( <boolean expression> ) ;
Statement
(loop body)
Boolean Expression
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 15
Control Flow of do-while
int sum = 0,number = 1
sum += number;
number++;
sum <=
1000000?
true
false
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 16
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) );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 17
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");
repeat = false;
}
else {
sum += num;
if (sum > 1000) { //pass the threshold
messageBox.show("Sum became larger than 1000");
repeat = false;
}
}
} while ( repeat );
Terminates the
loop by setting
the boolean
variable to false.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 18
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?”);
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 19
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;
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 20
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?");
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 21
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" );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 22
ResponseBox Methods
CLASS,ResponseBox
Method Argument Description
<constructor> MainWindow Creates a ResponseBox object.
<constructor>
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,
String
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.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 23
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 ).
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 24
for ( i = 0 ; i < 20 ; i++ ) {
number = inputBox.getInteger();
sum += number;
}
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Initialization Boolean Expression Increment
Statement
(loop body)
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 25
Control Flow of for
i = 0;
false
number =
inputBox.getInteger( );
sum += number;
true
i ++;
i < 20?
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 26
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
for (int k = 100; k > 0; k--) )3
k = 100,99,98,97,...,1
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 27
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,
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 28
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
}
INNE
R
OU
TE
R
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 29
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 10
leftAlign
centerAlign
rightAlign
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 30
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 ));
20
leftAlign
centerAlign
rightAlign
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 31
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
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 32
Methods in The Format Class
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 33
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 {
1,Generate a secret number;
2,Play one game;
} while ( the user wants to play );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 34
HiLo – Design
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 35
HiLo – Object Diagram
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 7 - 36
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