Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(Syntax)
(Uses)
Line 27: Line 27:
 
     done = JOptionPane.showInputDialog("Enter a phrase, type quit to finish");
 
     done = JOptionPane.showInputDialog("Enter a phrase, type quit to finish");
 
      
 
      
     while(!done.equals("quit")) {
+
     while(!done.equals("quit"))
      System.out.println("Hello " + name);
+
    {
      done = JOptionPane.showInputDialog("Enter a phrase, type quit to finish");
+
        System.out.println("Hello " + name);
 +
        done = JOptionPane.showInputDialog("Enter a phrase, type quit to finish");
 
     }
 
     }
 
   }
 
   }

Revision as of 21:44, 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