next up previous
Next: Equivalence between while loop Up: Unit 06 Previous: Observations on the do

Example of a do loop: input validation

Often it is necessary to validate data input by the user, and repeat the request for the data in the case where the input of the user is not valid. This can be done by using a do loop.

Example: Write a public static method that continues reading from input an integer until the integer is positive, and then returns the positive integer that has been input.

public static int readPositiveInteger() {
  int i;
  do {
    i = Integer.parseInt(JOptionPane.showInputDialog(
                           "Input a positive integer"));
  } while (i <= 0);
  return i;
}

Note that the previous method is not able to handle correctly all situations of incorrect input, for example, the situation where the user inputs an alphabetical character (or any sequence of characters that cannot be parsed by parseInt()). We will see later on how Java allows us to handle such situations through the use of exceptions.


next up previous
Next: Equivalence between while loop Up: Unit 06 Previous: Observations on the do