While Loops

From CompSciWiki
Revision as of 22:23, 5 December 2007 by Nick (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

The while loop is the most basic form of a loop. The loop continues to repeat as long as the test condition evaluates to true.

   

{{{Body}}}

Syntax

In java, the while loop takes the form of

while(test_condition)
{
   ...
   statements;
   ...
}

The while will execute all of the instructions inside of the block of code following it. The instructions in the block of code will execute as long as the test condition is true. When the test condition evaluates to false the program continues with the instructions following the block.

Uses

While loops are very useful in any situation where a certain section of code needs to be repeated while a certain condition is true. For example: If you want to loop until the user gives specific input. Below is an example of a while loop that iterates until the user enters the string 'quit'.

import javax.swing.JOptionPane;

public class Input
{
  public static void main(String args[]) 
  {
    String name;
    name = JOptionPane.showInputDialog("Enter a name, type quit to finish");
    
    while(!name.equals("quit"))
    {
         System.out.println("Hello " + name);
         name = JOptionPane.showInputDialog("Enter a name, type quit to finish");
    }
  }
}

The instruction !name.equals("quit") is the test condition. It evaluates to true until quit is entered.