Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(Uses)
m (Uses)
Line 34: Line 34:
 
</pre>
 
</pre>
  
This could will repeatedly ask the user for input, and display that input, until the user types quit.
+
This code will repeatedly ask the user for input, and display that input, until the user types quit.

Revision as of 17:55, 4 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 false.

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.