next up previous
Next: Loop scheme for characteristic Up: Unit 06 Previous: Loop scheme for an

Loop scheme for characteristic values in a set: maximum with a known interval

Let us consider the problem of finding the maximum of a set of integers in input. Assume that:

String s;       // current string in input
int n;          // current integer
int max;        // current maximum

max = -1;
s = JOptionPane.showInputDialog("Input an integer");
while (s != null) {
  n = Integer.parseInt(s);
  if (n > max) max = n;
  s = JOptionPane.showInputDialog("Input an integer");
}

if (max == -1)
  System.out.println("empty set of values");
else
  System.out.println("maximum = " + max);

Note: If the user does not input any integer, then the computed maximum value is -1. Since -1 is not in the interval of allowed values (we have assumed that all integers are greater than or equal to 0), it can never be returned in the case where the user inputs at least one value. Therefore, in this case, we can use the comparison of the result with -1 as a means to detect whether the user has input at least a value or not.


next up previous
Next: Loop scheme for characteristic Up: Unit 06 Previous: Loop scheme for an