Transcript Chapter 6

Chapter 6
Repetition Statements
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6 Objectives
After you have read and studied this
chapter, you should be able to
• Implement repetition control in a program
by using while statements.
• Implement repetition control in a program
by using do-while statements.
• Implement a generic loop-and-a-half
repetition control statement.
• Implement repetition control in a program
by using for statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6 Objectives, cont.
After you have read and studied this
chapter, you should be able to
• 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 by
using the showConfirmDialog method
from the JOptionPane class.
• (Optional) Write simple recursive methods.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.1 The while Statement
Repetition statements control a block of
code to be executed for a fixed
number of times or until a certain
condition is met.
Java has three repetition statements:
• while
• do-while
• for
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.1 The while Statement
In Java, while statements follow a
general format:
while ( <boolean expression> )
<statement>
For example:
int sum = 0, number = 1;
while (number <= 100){
sum = sum + number;
number = number + 1;
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.1 The while Statement
Repetition statements are also called loop
statements, and the <statement> is
known as the loop body.
As long as the <boolean expression>
is true, the loop body is executed.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.1
Correspondence of the example while
statement to the general format.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.2
A diagram showing the control flow of a
while statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.1 The while Statement
In a count-controlled loop, the loop body
is executed a fixed number of times.
In a sentinel-controlled loop, the loop
body is executed repeatedly until a
designated value, called a sentinel, is
encountered.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.2 Pitfalls in
Writing Repetition Statements
When writing repetition statements, it is
important to ensure that the loop will
eventually terminate.
There are several different types of
potential programming problems we
should keep in mind as we develop
our programs.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.2 Pitfalls in
Writing Repetition Statements
Infinite loop
int product = 0;
while (product < 5000) {
product = product * 5;
}
Because product is initialized to 0,
product will never be larger than 5000
(0 = 0 * 5), so the loop will never
terminate.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.2 Pitfalls in
Writing Repetition Statements
Overflow error
int count = 1;
while (count != 10) {
count = count + 2;
}
In this example, (the while statement of
which is also an infinite loop), count will
equal 9 and 11, but not 10.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.2 Pitfalls in
Writing Repetition Statements
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.2 Pitfalls in
Writing Repetition Statements
Real numbers should not be used in
testing or increment, because only an
approximation of real numbers can be
stored in a computer.
The off-by-one error is another
frequently-encountered pitfall.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.3 The do-while Statement
The while statement is a pretest loop,
because the test is done before the
execution of the loop body. Therefore,
the loop body may not be executed.
The do-while statement is a posttest
loop. With a posttest loop statement,
the loop body is executed at least
once.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.3 The do-while Statement
The format of the do-while statement is:
do
<statement>
while (<boolean expression>);
The <statement> is executed until the
<boolean expression> becomes
false.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.3 The do-while Statement
int sum = 0, number = 1;
do{
sum += number;
number++;
} while (sum <=1000000);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.3
Correspondence of the example dowhile statement to the general format.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.4
A diagram showing the control flow of
the do-while statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.4 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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.4 Loop-and-a-Half Repetition 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.”);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.5
A diagram showing the control flow of a
loop-and-a-half statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.4 Loop-and-a-Half Repetition 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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.4 Loop-and-a-Half Repetition Control
• 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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.5 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);
Executing the code above will result in Fig.
6.6.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.6
A confirmation dialog created by using
the showConfirmDialog method of
the JOptionPane class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.5 Confirmation Dialog
Used in a loop statement:
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);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
The format of the for statement is as
follows:
for (<initialization>; <boolean expression>;
<increment>)
<statement>
int i, sum = 0;
for (i = 1,i <=100, i++){
sum += i; //equivalent to sum = sum + 1;
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.7
Correspondence of the example for
statement to the general format
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.8
A diagram showing the control flow of
the example for statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
The variable i in the example
statement is called a control variable.
It keeps track of the number of
repetitions.
The <increment> can be by any
amount, positive or negative.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
/*
Chapter 6 Sample Program: Dropping a
Watermelon
File: Ch6DroppingWaterMelon.java
*/
import javabook.*;
import java.io.*;
class Ch6DroppingWaterMelon {
public static void main( String[] args )
throws IOException {
double
initialHeight,
position,
touchTime;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
BufferedReader bufReader =
new BufferedReader(
new InputStreamReader( System.in ));
System.out.print("Initial Height:");
InitialHeight=Double.parseDouble(bufReader.
readLine( ));
touchTime = Math.sqrt(initialHeight /16.0);
touchTime = Math.round(touchTime * 10000.0)
/ 10000.0;
//convert to four decimal places
System.out.println("\n\n
Time t
Position at Time t \n");
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
for (int time = 0; time < touchTime;
time++) {
position = -16.0 * time*time +
initialHeight;
System.out.print("
" + time);
System.out.println("
position);
" +
}
//print the last second
System.out.println("
"
0.00");
" + touchTime +
System.out.println("\n\n\n");
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.6 The for Statement
An illustration of the
Ch6DroppingWaterMelon.java
program.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.9
The positions of a watermelon dropped
from a height of 500 ft.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.7 Nested-for Statements
Nested-for statements are for statements
embedded within other for statements.
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(“”);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.10
The price table for carpets ranging in
size from 11 × 5 to 20 × 25 ft. whose
unit price is $19 per sq. ft.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.7 Nested-for Statements
The outer for statement ranges from the
first row (width = 11) to the last row
(width = 20).
For each repetition of the outer for, the
inner for statement is executed, which
ranges from the first column (length =
5) to the fifth (length = 25).
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
To align values with varying numbers of
digits, we must vary the number of
spaces in front of the values.
The idea behind formatted output is to
allocate the same amount of space for
the output values and align the values
within the allocated space.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.11
The price table for carpets with $15 per
sq. ft. and width ranging from 5-14 ft.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.12
How to place a varying number of
spaces to align the output values.
Hyphen is used here to indicate the
blank space.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
We will define a noninstantiable helper
class called Ch6Format.
The pad method has an integer
argument and returns a String object
with the specified number of blank
spaces.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
/*
Chapter 6 Sample Program: Simple formatting
class
File: Ch6Format.java
*/
/**
class Ch6Format {
private static final String DEFAULT_SYMBOL
= " "; //blank space
public static String pad(int size) {
return pad(size, DEFAULT_SYMBOL);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
public static String pad(int size, String
symbol) {
String result = "";
for (int i = 0; i < size; i++) {
result += symbol;
}
return result;
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.13
There are two versions of the pad
method. The first returns the specified
number of blank spaces. The second
returns the specified number of
designated symbols. Hyphen is used
here to indicate blank space.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
/*
Chapter 6 Sample Program: Sample formatting
statements
File: Ch6CarpetPriceTableWithFormat.java
*/
//import javabook.*;
import java.io.*;
class Ch6CarpetPriceTableWithFormat
{
public static void main (String[] args)
{
String numStr;
int
int
int
valueWidth = 8;
labelWidth = 3;
price;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
PrintStream output = System.out;
//print out the column labels
output.print(Ch6Format.pad(labelWidth));
for (int colLabel = 5; colLabel <=25; colLabel +=
5) {
numStr = Integer.toString(colLabel);
output.print(Ch6Format.pad(valueWidth numStr.length()) + numStr);
}
output.print("\n\n");
for (int width = 5; width <= 14; width++) {
numStr = Integer.toString(width);
output.print(Ch6Format.pad(labelWidth numStr.length()) + numStr);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.8 Formatting Output
for (int length = 5; length <= 25; length += 5) {
price = width * length * 15;
numStr = Integer.toString(price);
output.print(Ch6Format.pad(valueWidth numStr.length()) + numStr);
}
next row
//
}
//finished one row; now move on to the
output.print("\n");
output.print(newLine);
output.println("\n\n\n");
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 6.14
Carpet price table of Fig. 6.11 with
proper alignment.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
The goal of this exercise is to design a
program that generates a loan table.
The table will compare different
monthly payments for a set loan
amount, with varying loan periods in
each column and different interest
rates in each row.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
The start method can be expressed as
tell the user what the program does;
prompt the user “Do you want to
generate a loan table?”;
while (the user says YES){
input the loan amount;
generate the loan table;
prompt the user “Do you want
another loan table?”;
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
The start method was expressed in
pseudocode.
Pseudocode is an informal language
used to express an algorithm.
It is useful in clarifying the purpose or
function of the program without being
tied down to the syntactic rules of a
programming language.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
public void start () {
int response;
describeProgram();
response = prompt(“Generate a loan table?”);
while (response == JOptionPane.YES_OPTION){
loanAmount = getLoanAmount(); //get input
generateLoanTable(loanAmount);//generate
table
response = prompt(“Generate another loan
table?”);
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
private int prompt(String question){
int reply;
reply = JOptionPane.showConfirmDialog(null,
question,
“Confirmation”,
JOptionPane.YES_NO_OPTION);
return reply;
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
Other methods in the program:
describeProgram: tells the user what
the program does if the user requests
it.
getLoanAmount: gets the loan amount
from the user.
generateLoanTable: generates the
loan table.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.9 Loan Tables
To compute the monthly loan payment,
reuse the Loan class defined in
Chapter 4.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
The method random is called a
pseudorandom number generator and
returns a number of type double that
is greater than or equal to 0.0 but less
than 1.0.
The generated number is called a
pseudorandom number because it is
not truly random.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
If we want to generate an integer, and
the number returned from the random
method ranges from 0.0 up to (but not
including) 1.0, we must perform a
conversion so the number will fall
within the desired range.
Use the formula:
Y = {X × (max – min + 1)} + min
where X is the number returned by
random.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
The formula is thus expressed in Java:
//assume correct values are assigned to
//‘max’ and ‘min’
int randomNumber
= (int) (Math.floor(Math.random *
max-min+1)) + min);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
The following program generates N
random numbers between 1 and 4 to
simulate the suit of a drawn card.
It keeps one counter for each suit, and
increments the matching counter after
a random number is generated.
At the end of the generation, it prints the
ratio count/N.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
/*
Chapter 6 Sample Program: Test the random number
generator
File: Ch6TestRandomGenerator.java
*/
import javax.swing.*;
import java.util.*;
class Ch6TestRandomGenerator {
private
private
private
private
static
static
static
static
final
final
final
final
int
int
int
int
CLUB
SPADE
HEART
DIAMOND
=
=
=
=
1;
2;
3;
4;
public static void main( String[] args ) {
Ch6TestRandomGenerator tester = new
Ch6TestRandomGenerator();
tester.start();
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
public void start( ) {
long N;
while (keepTesting()) {
N = getSize();
generate(N);
}
}
private long getSize( ) {
String inputStr;
long
size;
while (true) {
inputStr = JOptionPane.showInputDialog(null,
"Enter size:");
size = Long.parseLong(inputStr);
if (size > 0) break; //input okay so exit
JOptionPane.showMessageDialog(null, "Input
must be positive");
}
return size;
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
private void generate(long size) {
Date startTime, endTime;
int suit;
long clubCnt, spadeCnt, heartCnt, diamondCnt;
clubCnt = spadeCnt = heartCnt = diamondCnt = 0;
startTime = new Date();
for (int i = 0; i < size;
i++) {
suit = getRandom(CLUB, DIAMOND);
switch (suit) {
case CLUB:
clubCnt++;
break;
case SPADE:
spadeCnt++;
break;
case HEART:
heartCnt++;
break;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
case DIAMOND: diamondCnt++;
break;
default: //default case should never happen
JOptionPane.showMessageDialog(null,
"Internal Error");
System.exit(0); //terminate the program
}
}
endTime = new Date();
System.out.println("N is " + size + "\n");
System.out.println("Club:
" + clubCnt
(double)clubCnt/size);
System.out.println("Spade:
" + spadeCnt
(double)spadeCnt/size);
System.out.println("Heart:
" + heartCnt
(double)heartCnt/size);
System.out.println("Diamond: " + diamondCnt
(double)diamondCnt/size);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
+ "
" +
+ "
" +
+ "
" +
+ "
" +
6.10 Random Number Generation
double elapsedTimeInSec = (double)
(endTime.getTime() - startTime.getTime())/1000.0;
System.out.println("Elapsed time (sec): " +
elapsedTimeInSec );
System.out.println("\n");
}
private int getRandom(int min, int max) {
int randomNumber = (int) (Math.floor(Math.random() *
(max-min+1)) + min);
return randomNumber;
}
private boolean keepTesting( ) {
boolean result;
int response = JOptionPane.showConfirmDialog(null,
/*prompt*/
"Perform Test?",
/*dialog title*/
"Random Number Generator",
/*button options*/
JOptionPane.YES_NO_OPTION);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
6.10 Random Number Generation
if (response == JOptionPane.YES_OPTION) {
result = true;
} else {
result = false;
}
return result;
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.