Reputation: 15
Purpose of this code: Find the lowest integer inserted by a user.
Problem facing: When the variable thirdInt
is supposed to be the lowest number, the console doesn't print out the result.
Can anybody tell me what is wrong with that part of my code?
import java.util.Scanner;
public class FindMinimum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first integer:");
int firstInt = input.nextInt();
System.out.println("Enter the second integer:");
int secondInt = input.nextInt();
System.out.println("Enter the third integer:");
int thirdInt = input.nextInt();
if(firstInt<secondInt || firstInt == secondInt) {
if(firstInt<thirdInt || firstInt == thirdInt) {
System.out.println("The minimum is " + firstInt);
}
}
else if(secondInt<firstInt || secondInt == firstInt) {
if(secondInt<thirdInt || secondInt == thirdInt) {
System.out.println("The minimum is " + secondInt);
}
}
else if(thirdInt<firstInt || thirdInt == firstInt) {
if(thirdInt<secondInt || thirdInt == secondInt) {
System.out.println("The minimum is " + thirdInt);
}
}
}
}
Upvotes: 0
Views: 70
Reputation: 794
The answer can be very simple like the following (Like what Matthew0898 had said in the comment)
int answer = firstInt;
if secondInt < answer {
answer = secondInt;
}
if thirdInt < answer {
answer = thirdInt;
}
System.out.println("The minimum is " + answer);
Upvotes: 3
Reputation: 6637
Check what you have done with you first two outer if
statements:
if(firstInt<secondInt ...)
else if((secondInt<firstInt ...)
The only way for anything to be passed down to the third if
statement is if firstInt==secondInt
, which was also eliminated by your || secondInt == firstInt
.
Rather than what you had, you probably want something like:
if(firstInt <= secondInt && firstInt <= thirdInt)
{
System.out.println("The minimum is " + firstInt);
}
else if(secondInt <= thirdInt)
{
System.out.println("The minimum is " + secondInt);
}
else
{
System.out.println("The minimum is " + thirdInt);
}
Upvotes: 1