While Loops
Introduction.
Now we want to present a bit more about looping when not as much can be
pre-determined about the stopping and starting values. This will fit
under the aegis of while loops. Here the looping is based on more abstract criteria so that the looping continues while an expression evaluates to true. The standard syntax for a for loop conforms to the following while (expression) structure.
The criteria within the parentheses can be quite different. If there is only a single code statement after the while (expression) there doesn't need to be any braces.
Some Verbal Examples. Assume you have just bought a car on a five year plan with monthly payments. Maybe you make some early payments or some payments that are larger than required. You might get the following oversimplified code segment.
Well, this can go on and on. Obviously, some of these depend on having other sources for inputs. A Simple Code Example. We will again find the sum of some integers starting at one. But now we will ask the user whether they want to continue after each iteration. You should call the application SumOfNAsYouGo.java. |
import javax.swing.JOptionPane; public class SumOfNAsYouGo {
} // end SumOfNAsYouGo |
We do our typical imports, declarations and
initializations so I won't discuss these any more. We don't do our
typical error trapping on the inputs and for the parsing. Of greater
interest is the while loop.
There showInputDialog( ) looks largely like the following at each step. |