Lecture 5-2: while loops
After reading through Chapter 5, you should be able to
- Use the
++and--operators - Explain the difference between prefix and postfix modes
- Explain what a loop is
- Write
whileloops - Write simple count-controlled loops
- Use loops that validate user input
- Use loops that calculate the running total of a series of numbers
- Write loops that are terminated by a sentinel value
- Write loops using
do-while, andfor - Use nested loops
- Determine which loops are best for different circumstances
- Write code that saves data to text files and reads data from text files
Today's Learning Objectives
- Know the three type of looping constructs in Java
- Know how to write loops in Java using
whilestatements - Know how to validate user input using a loop
Loops
Loop statements allow us to execute a Java statement(s) multiple times repetitively. Like if statements, they are controlled by boolean expressions
Java has three kinds of loop statements:
whileloopdo-whileloopforloop
The programmer must choose the right kind of loop for the situation
The while Statement
The while statement has the following syntax:
while ( boolean expression )
{
statement(s);
}
while is a reserved word in Java.
- The boolean expression inside the parenthesis is called the loop condition
- The statement(s) inside the block are called the loop body
Each time the loop body is executed, the condition is checked. If the loop condition is true, the loop continues to execute.
If the loop condition is false, the loop terminates.
The loop body is executed repetitively until the condition becomes false. One single cycle of the loop is called an iteration.
Simple count-controlled while loop
int count; count = 1;while(count<=5) { System.out.println(count); count = count + 1; } System.out.println ("Done");
Infinite Loops
- Care must be taken to set the condition to
falsesomewhere in the loop so the loop will end. - Loops that do not end are called infinite loops.
- A while loop executes 0 or more times since if the condition is false, the loop will not execute.
Error checking user input
while loops are often used to check for valid user input, looping repetitively until the user gets it right!
int number; Scanner keyboard = new Scanner (System.in); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); // Validate the inputwhile((number < 1)||(number > 100)) { System.out.println("That number is invalid."); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); }