Difference between revisions of "Do-While Loops"

From CompSciWiki
Jump to: navigation, search
m
(Example: showInputDialog doesn't need the null)
Line 20: Line 20:
  
 
<pre>
 
<pre>
String inp;
+
String input;
int userInp;
+
int userInput;
 
do {  
 
do {  
   inp = JOptionPane.showInputDialog(null,"Enter a positive integer");
+
   input = JOptionPane.showInputDialog("Enter a positive integer");
   userInp = Integer.parseInt(inp);
+
   userInput = Integer.parseInt(input);
} while (userInp <= 0);
+
} while (userInput <= 0);
 
</pre>
 
</pre>

Revision as of 02:25, 8 October 2008

COMP 1010 Home > Loops


Introduction

The do-while loop is similar to a while loop, except that the condition is tested at the bottom of the loop.

   

{{{Body}}}

A do-while loop is similar to a while loop, except that the boolean test is done at the bottom of the loop. This can be more natural in some loops, but the do-while loop is perhaps not as frequently used as while loops, since with a little manipulation, you can rewrite any do-while loop as a regular while loop.

Syntax

do { 
   stmts;
} while (boolExpr);

Note that there is a semicolon after the boolean expression.

One important point to note about do-while loops is that the loop will always execute once: the boolean condition is not tested until the bottom of the loop, 'after the loop body has been executed once. This may make things easier in some cases, but it may not be what you want in other cases. Make sure that if you're using a do-while loop, it makes sense that the code inside the loop is executed at least once.

Example

Here's an example which repeatedly asks the user for an input until the input is a positive number:

String input;
int userInput;
do { 
   input = JOptionPane.showInputDialog("Enter a positive integer");
   userInput = Integer.parseInt(input);
} while (userInput <= 0);