jhedm jhedm -4 years ago 78
Java Question

Determining the highest and lowest number (Java)

I'm currently writing a program where the user must input 10 numbers and then the output will be the highest number and the lowest number. There is something wrong in my code but couldn't find it. Here is my code:

int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);


for(int i=0; i<10; i++){

System.out.print("Enter a number:");
num = scan.nextInt();
}

if (num > highest){

highest = num;
}

else if(num < lowest){

lowest = num;
}

System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);

Answer Source

Initialise your values differently:

int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;

If you initialise them both to zero, you will never have a "highest" value below zero, or a "lowest" value above zero

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download