Kaiju :
My programs asks the user to input integers (on a loop) until they input -99; which will then display the highest and lowest numbers of the input integers. I have a variable called count, that increments every time the user puts in a new integer, to keep track of the number of integers inputted by the user. How can I have -99 not included as one of the integers and not incrementing count?
Code:
//variables
int num = 0, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
low = num;
high = num;
//loop
while(num != -99){
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++;
if (num == -99 && count == 0)
{
count--;
System.out.println("You did not enter a number");
} //outer if end
else {
//higher or lower
if(count > 0 && num > high)
{
high = num;
} //inner else end
else if(count > 0 && num < low)
{
low = num;
} //inner else if end
else
{
} //inner else end
} //outer else end
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
Azhar :
You approach is good, but you missed some points,
- your condition to find max or min is also wrong because you have to write them separately.
- User Entered any value or not, you have to decide this outside the loop.
- You have to initialize high and low with first input. I am trying to make some correction in your program, just changing the required part. Hope it will help you.
//variables
int num = 0, count = 0, high =0 , low = 0;
Scanner userInput = new Scanner(System.in);
//loop
while(true){
//Using infinite loop, we will break this as per condition.
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
if(num == -99)
{
break;
}
count++;
if(count == 1)
{//initialize high and low by first number then update
high = num;
low = num;
}
//to check highest
if(num > high)
{
high = num;
}
//to check smallest
if(num < low)
{
low = num;
}
}
if (count == 0)
{//Here we check that if user enter any number or directly entered -99
System.out.println("You did not enter a number");
}
else
{
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=370842&siteId=1