Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(Introduction)
(Introduction)
Line 1: Line 1:
 
==Introduction==
 
==Introduction==
The while loop is a special form of [[Loops|loop]] that will continue to repeat as long as the [[test condition]] evaluates to '''true'''.
+
The while loop is a special form of [[Loops|loop]] that will continue to repeat as long as the [[test condition]] evaluates to ''true''.
  
 
==Syntax==
 
==Syntax==

Revision as of 21:43, 7 March 2007

Introduction

The while loop is a special form of loop that will continue to repeat as long as the test condition evaluates to true.

Syntax

In java, the while loop takes the form of

while(test condition) {
   ...
   statements
   ...
}

In this particular situation, the while loop will continue to iterate as long as the test condition evaluates to true

Uses

A while loop is useful in any situation where you don't know beforehand how often you want to repeat the block of code. Consider the following situation instance:

import javax.swing.JOptionPane;

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

This code will repeatedly ask the user for input, and display that input, until the user types quit.

Back to Loops