In the case of the do-while statement, the body
of the loop executes before the code checks the loop condition. When a program must execute a block of code
at least once, the do-while may be the best choice for controlling a loop. Here is code to use the do-while
statement instead of the while statement for reading the file Students:
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
String score;
do {
score = in.readLine();
total = total + Double.parseDouble( score );
} while( score != null )
At first glance, it looks like this version saves code. However, in this particular case, this code exposes us
to danger. If the file should ever be empty, the first call to parseDouble will cause the program to fail with
a run-time exception, because Double.parseDouble cannot parse a null value. In this application, we
would do better to use the while instead of the do-while.
This is the syntax of the do-while loop:
do
while( );
The loop body can be, and usually is, a code block framed by curly braces. As long as the loop condition
remains true, the loop body will execute again and again. The do-while structure is particularly appropriate
when you require the loop body to execute at least once every time the program runs.
Pages:
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206