Lesson-2 3
Lesson-2 3
while (expression)
{
[Java code block to repeat while expression is true]
}
In this structure, all code between the curly braces is repeated
while the given logical expression is true.
In the while loop, if expression is always true, you will loop forever
– something called an infinite loop.
counter = 10;
while (counter > 0)
{
counter = counter - 1;
}
Example 2 (assuming we have a Random object named my
Random):
rolls = 0;
counter = 0;
while (counter < 10)
{
roll = roll + 1;
if ((myRandom.nextInt(6) + 1) == 6)
{
counter = counter + 1;
}
}
This loop repeats while the counter variable remains less than 10.
The counter variable is incremented (increased by one) each time a
simulated dice rolls a 6. The roll variable tells you how many rolls
of the dice were needed to roll 10 sixes.
If the logical expression used by a while loop is false the first time
the loop is encountered, the code block in the while loop will not
be executed.
Another looping structure in Java that will always be executed at
least once.
do
{
[Java code block to process]
}
while (expression);
Unlike the while loop, there is a semicolon at the end of the while
statement.
The code block in the braces repeats ‘as long as’ the boolean-
valued expression is true.
Example: Keep adding three to a sum until the value exceeds 50.
sum = 0;
do
{
sum = sum + 3;
}
while (sum <= 50);
Another dice example:
sum = 0;
roll = 0;
do
{
sum = sum + myRandom.nextInt(6) + 1;
roll = roll + 1;
}
while (sum <= 30);
This loop rolls a simulated dice while the sum of the rolls does not
exceed 30. It also keeps track of the number of rolls (roll) needed
to achieve this sum.
When you exit a while loop, processing continues at the next Java
statement after the closing brace.
If, at some point in the code block of a loop, you decide you need
to immediately leave the loop, this can be done using a Java break
statement.
When a break statement is encountered, processing is
immediately transferred to the Java statement following the loop
structure.
sum = 0;
roll = 0;
do
{
// Roll a simulated die
die = myRandom.nextInt(6) + 1;
if (die == 5)
{
break;
}
sum = sum + die;
roll = roll + 1;
}
while (sum <= 30);