Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
Line 1: Line 1:
{{1010Topic|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''.}}
+
{{1010Topic|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''.|Chapter_TOC=[[Loops]]}}
  
 
==Syntax==
 
==Syntax==

Revision as of 21:47, 21 March 2007

COMP 1010 Home > Loops


Introduction

The while loop is a special form of loop that will continue 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
   ...
}

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.