Mental Overload
Mental Overload

Reputation: 65

how to properly check min/max inputs

this is my code.

  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();
} while(num != -1);{
if (num < min) {
min = num;
} if (num > max) {
max = num;
}
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);

the max is always -1 and the min is always -1 neither of those should return -1

help

Edited in response to obvious mistakes, still not the correct code tho.

Upvotes: 0

Views: 203

Answers (2)

pmatatias
pmatatias

Reputation: 4404

the condition is not correct, should be:

if (min > num)

because in the top you declare

int min = Integer.MAX_VALUE

actual value of the this is : 2^31-1 = 2147483647

Upvotes: 1

there is no possible int that can meet the condition

if (min < num) {

because min is pointing to the max allowed integer

min = Integer.MAX_VALUE;    //2^31 - 1.

Upvotes: 1

Related Questions