Java TOPIC 20 – WHILE LOOPS, Part 2 LESSON NOTE THE BREAK STATEMENT The
break statement allows you to exit the while loop at any point inside the
loop. It appears alone on the line followed by a semicolon.
while(booleanExpression) { . . . if (booleanExpression) { break; } . . . } Many
programming theorists (like your favourite teacher
Mr. Campeau) believe that the break statement should almost never be used
because:
EXAMPLE – DICE ROLLER while(true) { System.out.println("Are
you ready for a dice roll? (n=no)"); String
answer = scr.nextLine(); if(answer.equals("n")) { break; } int roll = (int)(Math.random()*6+1);
//1 to 6 System.out.println("You roll a " + roll); } DO-WHILE LOOP TEMPLATE The
do-while loop is identical to the while loop except the statement block is
executed once before the boolean expression is
checked to see if it is true. Here
is the template: do { //statement block } while (booleanExpression) We
will mostly focus on the while loop instead of the do-while loop. One can use
either one at all times. COMMON ERRORS
|
|
|