Difference between revisions of "While Loops"
From CompSciWiki
(→Introduction) |
(→Syntax) |
||
Line 5: | Line 5: | ||
In java, the while loop takes the form of | In java, the while loop takes the form of | ||
<pre> | <pre> | ||
− | while(test condition) { | + | while(test condition) |
+ | { | ||
... | ... | ||
statements | statements |
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.