I know it's probably something small that I'm doing wrong. I want it to print the lowest number etc. at the end of the loop, but it always prints zero as lowest. How do I get it to not put the exit mechanism zero as the lowest number.
Any advice please?
class HighLowAve
{
public static void main (String[]args)
{
int num =0;
int sum;
int highest;
int lowest;
int index;
Double average;
highest = num;
lowest = num;
sum = 0;
index = 0;
do
{
System.out.println("Enter a number. Press zero to quit ");
num = EasyIn.getInt();
if (num > highest)
{
highest = num;
}
else if (num < lowest)
{
lowest = num;
}
sum = sum + num;
index++;
}while (num !=0);
average = (double) sum/(index-1);
System.out.println("The highest number was " + highest);
System.out.println("The lowest number was " + lowest);
System.out.println("The average number was " + average);
}
}
Your highest
and lowest
variables both start at 0. So if your numbers are all negative, you'll get a highest
of 0, incorrectly. If your numbers are all positive, you'll get a lowest
of 0, incorrectly.
Just start off with highest = Integer.MIN_VALUE
and lowest = Integer.MAX_VALUE
and then the first iteration will end up with the correct highest
and lowest
value.
First check if the number is zero before changing the high and low values.
do
{
System.out.println("Enter a number. Press zero to quit ");
num = EasyIn.getInt();
if (num == 0) break;
if (num > highest)
{
highest = num;
}
else if (num < lowest)
{
lowest = num;
}
sum = sum + num;
index++;
}while (num !=0);
Also you need to initialize highest
and lowest
before you do any comparisons on them in the loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.