Java Notes‎ > ‎

while and do-while

The while Statement

The while statement allows for repeating a section of code. The syntax of the command is:

while (expression)
	action;

Put the "action" inside braces ( { } ) if you have multiple statements you want included in the loop. The expression determines when the loop ends. If the loop ending expression is true, the statement(s) in the "action" part are executed. Just as with the if statement, in the (expression) we can use the following relational operators:

<

less than

>

greater than

!=

not equal to

==

equal to

<=

less than or equal to

>=

greater than or equal to

For instance, we could use the while loop to handle a menu option as follows:

int menuOption;
...
System.out.print("Enter menu option: "); menuOption = keyboard.nextInt(); while (menuOption > 5) { System.out.print("Invalid entry, please enter a new option: "); menuOption = keyboard.nextInt(); }

As described for the if statement, the boolean operators && and || can be used as well.

The do-while Statement

The while statement may not execute at all, depending on the expression used as the loop ending condition. In contrast, the do-while statement always executes at least once, such as when handling menuOptions. The syntax of the command is:

do  {
	action;
} while (expression);

For instance:

int menuOption;
...
do { System.out.print("Enter menu option: "); menuOption = keyboard.nextInt(); if ( menuOption > 5) { System.out.print("Invalid entry, please enter a new option: "); continue; // Repeat loop from the top } } while (menuOption > 5)
Comments