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.

As soon as the break statement is executed, Java jumps to the line after the statement block.

TEMPLATE – WHILE with BREAK

 

  • Here is a general template of a while loop with a break statement inside. Notice that it is located inside an if-statement. Otherwise, the loop would never execute more than once.

 

while(booleanExpression)

{

   .

   .

   .

   if (booleanExpression)

   {

      break;

   }

   .

   .

   .

}

DON’T GIVE ME A BREAK

Many programming theorists (like your favourite teacher Mr. Campeau) believe that the break statement should almost never be used because:

    • It is difficult to read code with break statements.
    • It is always possible to rewrite the code to do the same thing without the statement.
    • Break statements cause confusion (AT&T lost 60 million over a break statement!)

 

EXAMPLE – DICE ROLLER

The following example generates a random dice roll (1 to 6).  But before generating the value, it waits for the user to press enter.  If the user enters "n", then the program ends; otherwise it continues to loop as long as the user wants more rolls.


            Scanner scr = new Scanner(System.in);

            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

 

  • All lines inside the statement block are to be indented. Forgetting to do so makes it difficult to read your code.

 

  • The line “while(booleanExpression)” should not have a semicolon at the end. Putting one creates an infinite loop.

  • The only way a while loop ends is if the condition (boolean expression) becomes false. Therefore, one must not forget to have a way for this to happen.