Java Programming
Control statements
while
The syntax of the while loop
while (booleanExpression)
{
statements
}
A loop that continues while choice is "y" or "Y"
String choice = "y"; while (choice.equalsIgnoreCase("y")) { // get the invoice subtotal from the user Scanner sc = new Scanner(System.in); System.out.print("Enter subtotal:"); double subtotal = sc.nextDouble(); // the code that processes // the user's entry goes here // see if the user wants to continue System.out.print("Continue? (y/n):"); choice = sc.next(); System.out.println(); }
A loop that adds the numbers 1 through 4 to sum
int i = 1; int sum = 0; while (i < 5) { sum = sum + i; i = i + 1; }
How to code while loops
- A while statement executes the block of statements within its braces as long as the Boolean expression is true. When the expression becomes false, the program exits the while statement.
- The statements in a while statement can be called a while loop.
- Any variables that are declared in the block of a while statement have block scope.
- If the Boolean expression in a while statement never becomes false, the statement never ends, so the program goes into an infinite loop. To cancel an infinite loop, close the console window or press Ctrl+C.
Code that uses while loop.
import java.util.*; public class WhileLoop { static Scanner console = new Scanner(System.in); static final int SENTINEL = -999; public static void main (String[] args) { int number; //variable to store number int sum = 0; //variable to store sum int count = 0; //variable to store total //numbers read System.out.println("Line 1: Enter positive integers " + "ending with " + SENTINEL);//Line 1 number = console.nextInt(); //Line 2 while (number != SENTINEL) //Line 3 { sum = sum + number; //Line 4 count++; //Line 5 number = console.nextInt(); //Line 6 } System.out.printf("Line 7: The sum of the %d " + "numbers = %d%n", count, sum); //Line 7 if (count != 0) //Line 8 System.out.printf("Line 9: The average = %d%n", (sum / count)); //Line 9 else //Line 10 System.out.println("Line 11: No input."); //Line 11 } }The console after the program finishes