Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^444) | Exceptions and Additional Control Structures
statement ends with a semicolon.
The dostatement
do
{
Statement1;
Statement2;
.
.
.
StatementN;
} while(Expression);
means “Execute the statements between doand whileas long as Expressionstill has the value
trueat the end of the loop.” In other words, you execute the statements before you test the
expression. Because whileappears at the end of the block, this statement is sometimes called
the do-whilestatement.
Let’s compare a whileloop and a doloop that perform the same task: They find the first
line that contains just a period in a file of data. We assume that the file contains at least one
such line.
whileSolution
inputStr = dataFile.readLine();
while(!inputStr.equals("."))
inputStr = dataFile.readLine();
doSolution
do
inputStr = dataFile.readLine();
while(!inputStr.equals("."));
The whilesolution requires a priming read so that inputStrhas a value before the loop
is entered. This preliminary activity isn’t required for the dosolution because the input state-
ment within the loop executes before the loop condition is evaluated.
We can also use the dostatement to implement a count-controlled loop if we know in
advance that the loop body should always execute at least once. Following are two versions
of a loop to sum the integers from 1 through n.
whileSolution
sum = 0;
counter = 1;
while(counter <= n)
{
sum = sum + counter;
counter++;
}

Free download pdf