Lecture 5-2: while loops

After reading through Chapter 5, you should be able to

Today's Learning Objectives

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:

  1. while loop
  2. do-while loop
  3. for loop

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.

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

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 input
   while ((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();
   }

URL: http://www.cwu.edu/~schwing/cs110/Java/notes/lecture5-2.html
Title: CS 110: Lecture Notes for Programming Fundamentals 1
Author: Ed Gellenbeck, Central Washington University
Last Updated: Monday, January 16, 2006