next up previous
Next: Other loop statements Up: Unit 06 Previous: Loop scheme for characteristic

Loop scheme for characteristic values in a set: maximum in the general case

Let us consider again the problem of finding the maximum of a set of reals in input. This time we make no assumption, i.e.,:

In this case, a possible solution is the following.

String s;          // current string in input
double r;          // current real
double max = 0;    // current maximum
boolean found;     // indicates whether at least one value was input

found = false;
s = JOptionPane.showInputDialog("Input a real");
while (s != null) {
  r = Double.parseDouble(s);
  if (!found || (r > max)) {
    max = r;
    found = true;
  }
  s = JOptionPane.showInputDialog("Input a real");
}

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

Note:

There are other means for determining the maximum in the general case discussed here. For example, we could exploit the fact that the wrapper class Double provides the constant MAX_VALUE holding the maximum value a double can have, and initialize the maximum to -MAX_VALUE. We would anyway need a boolean variable to distinguish the case where the user has input no number at all from the case where the user has input just -MAX_VALUE.

String s;          // current string in input
double r;          // current real
double max;        // current maximum
boolean found;     // indicates whether at least one value was input

found = false;
max = -Double.MAX_VALUE;

s = JOptionPane.showInputDialog("Input a real");
while (s != null) {
  r = Double.parseDouble(s);
  found = true;
  if (r > max) max = r;
  s = JOptionPane.showInputDialog("Input a real");
}

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


next up previous
Next: Other loop statements Up: Unit 06 Previous: Loop scheme for characteristic