i'm learning java and got a problem, I have an max/min exercise and tried the code bellow, for positive numbers it work fine, but when i try negative numbers the things got messy.
If you enter 5 you get min = 5 and max = 5, if you enter 10 after, you get min = 5 max = 10, so far so good, but if you type -5, you get min = -5 and max = -5, and things still get weirder, if you type 7, you get min =-5 and max = 7.
Can someone explain why this happens?
public static void main(String[] args) {
int ctrl;
int min = 0;
int max = 0;
boolean hasNextInt;
Scanner scanner = new Scanner(System.in);
int counter = 0;
while (true) {
System.out.println("Enter your number:");
hasNextInt = scanner.hasNextInt();
if(hasNextInt) {
ctrl = scanner.nextInt();
if(counter == 0) {
min = ctrl;
max = ctrl;
counter ++;
}
if(min>ctrl)
min = ctrl;
if(max<ctrl);
max = ctrl;
System.out.println("Minimum Number entered: " + min);
System.out.println("Maximum Number entered: " + max);
System.out.println("");
scanner.nextLine();
}else {
System.out.println("Invalid Number. Program stop working.");
break;
}
}
scanner.close();
}