next up previous
Next: Example of while loop: Up: Unit 06 Previous: The while loop

Use of a while loop for input

A while loop can be used to read from input a sequence of data, and to stop reading from input as soon as a certain condition becomes true. This is typically an indefinite loop.

Example: Read from input a set of strings and print them out on video until the user decides to stop.

String s = JOptionPane.showInputDialog("Input a string");
while (s != null) {
  System.out.println(s);
  s = JOptionPane.showInputDialog("Input a string");
}

Recall that JOptionPane.showInputDialog("...") returns null when the user presses the cancel button.

Example: Print the squares of integers read from input, until the user decides to stop.

int i;
String s;
s = JOptionPane.showInputDialog("Input an integer");
while (s != null) {
  i = Integer.parseInt(s);
  System.out.println(i*i);
  s = JOptionPane.showInputDialog("Input an integer");
}

General structure of an input loop

read the first element;
while (element is valid) {
  process the element;
  read the following element;
}


next up previous
Next: Example of while loop: Up: Unit 06 Previous: The while loop