0

Hey I'm trying to work out the minimum and maximum value from user input while disregarding the loop terminated value, which is -1. I understand how to do everything except how to disregard -1 when calculating minimum value for the input. Here's the code I've got so far:

    int value = 0;
    int max = value;
    int min = max;

    Scanner scan = new Scanner(System.in);

    while (value != -1) {
        System.out.print("Value: ");
        value = scan.nextInt();
        if (min > value) {
        min = value;     }

       if (max < value) {
           max = value; }
    }

    System.out.println("Min = " + min);
    System.out.println("Min = " + min);

How can I calculate the minimum value while disregarding -1?

Thanks.

peerliss
  • 45
  • 7

2 Answers2

1

You turn the loop into a never-ending loop, and add a break when termination number is detected:

Scanner scan = new Scanner(System.in);

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (;;) { // never-ending loop
    System.out.print("Value: ");
    if (! scan.hasNextInt()) {
        System.out.println("** Invalid input **");
        scan.nextLine(); // discard invalid input
        continue; // loop back to prompt again
    }
    int value = scan.nextInt();
    if (value == -1) // termination number
        break;
    if (value < min)
        min = value;
    else if (value > max)
        max = value;
}
System.out.println("Min = " + min);
System.out.println("Max = " + max);

Also fixed:

  • Initialization of min and max (otherwise min will likely always be 0)
  • Validation of Scanner input (so program doesn't die with exception on bad input)
  • Printing of max (was printing min twice)
  • Indentation (so code structure is clearly visible to human readers)
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • any reason you use an empty for loop instead of a while(true) loop? I've seen both idioms and always figured it's probably just programmer preference. – Austin Mar 30 '16 at 03:49
  • @AustinD It is entirely programmer preference. See http://stackoverflow.com/questions/8880870/java-for-vs-whiletrue – Andreas Mar 30 '16 at 03:52
0

Add if (value == -1) break; right before the line that starts withif (min > value). This causes the loop to break once the terminal (-1) character is read.

For clarity, you can then change your loop condition to while(true). This is a pretty common idiom for this situation.

Austin
  • 8,018
  • 2
  • 31
  • 37