I've made this java program to find the two smallest integers as inputted by the user. I think I'm pretty much just about there except there is one issue with my logic. I'm not sure what to set values:
int min, min2;
to where the rest of my program would work. I've tried -1 and 0 and it will just come out at the end as both my smallest and second smallest.
public class TwoSmall
{
public static void main(String[] args)
{
int input;
System.out.println("Enter you numbers: ");
input = IO.readInt();
int min = 0;
int min2 = 0;
while (input >= 0)
{
if (input < min)
{
min2 = min;
min = input;
}
else if (input < min2)
{
min2 = input;
}
input = IO.readInt();
}
System.out.println("The lowest number was " + min
+ " and the second lowest is " + min2);
}
}
Try setting min
and min2
to Integer.MAX_VALUE
. Practically this should solve your problem because the data type of integers you are working with is int
. But theoretically, setting min
and min2
to the first input value is the correct solution.
EDIT: As a matter of fact, I see that you input the first value separately. Hence the correct solution is as below:
public class TwoSmall
{
public static void main(String[] args)
{
int input;
System.out.println("Enter you numbers: ");
input = IO.readInt();
int min = input;
int min2 = input;
while (input >= 0)
{
numInputsGreaterThan1 = true;
if (input < min)
{
min2 = min;
min = input;
}
else if (input < min2)
{
min2 = input;
}
input = IO.readInt();
}
System.out.println("The lowest number was " + min
+ " and the second lowest is " + min2);
}
}
Note that in case, only a single integer is input, the value of min
and min2
printed will be the same.
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.