You want to test for max
and min
inside the loop and not after it terminates, since that means that you are only testing the last number that was entered – which will always be -1 (minus one). You also write that you want to ignore the -1. I believe the following code does what you require – which is to find the minimum and maximum of a series of numbers that are entered by the user.
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = 0;
do {
System.out.print("Type a number (or -1 to stop): ");
num = console.nextInt();
console.nextLine();
if (num != -1) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
} while (num != -1);
if (max == Integer.MIN_VALUE) {
System.out.println("No numbers were entered.");
}
else {
System.out.printf("max = %d , min = %d%n", max, min);
}
Note that you need to consume the <ENTER> key that the user presses after entering each number. Hence the call to method nextLine()
of class Scanner
. Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
If the first number entered is -1 then the user did not enter any numbers and therefore there will be no maximum or minimum. If the first number entered is -1, then the value of max
will be Integer.MIN_VALUE
.