Reputation:
I'm making a small program that determines the minimum integer of 3 integers. I'm having problems returning the integers back into the variable answer.
Here Is how I imagine the program working;
PROGRAM RUNS:
Code:
public class Method {
public static void main(String[] args) {
int answer = Minimum(20, 40, 50);
}
public static int Minimum(int first, int second, int third) {
if ((first < (second) && (first < third))) {
return first;
} else if ((second < (first) && (second < third))) {
return second;
} else if (((third < first) && (third < second))) {
return (third);
} else {
System.out.println("error");
}
}
}
Upvotes: 0
Views: 348
Reputation: 639
In Java 8+ your method could also look as follows:
public static int minimum(Integer val1, Integer val2, Integer val3){
List<Integer> list = Arrays.asList(new Integer[]{val1, val2, val3});
return list.stream().min((Integer v1, Integer v2) -> v1 < v2 ? 0 : 1 ).get();
}
Upvotes: 0
Reputation: 21
Minimum function should always return the integer value in any case. After else, add return statement.
Upvotes: 0
Reputation: 25980
You need to return a result in all cases, so your else
block is incorrect. Do you really think there is a fourth case ? No, there isn't : there are three integers so the minimum is one of those three, meaning there only are 3 cases... Simply remove the else
block. By the way, why do you use so many parentheses ? It's useless, and unreadable.
public static int Minimum(int first, int second, int third){
if (first < second && first < third)
return first;
else if (second < first && second < third)
return second;
else
return third;
}
As noted by the others, this is not sufficient to make your method correct. Indeed, you don't care about strict inequality here because when two numbers are the same, you can choose either of them as the minimum. This code breaks if the two first parameters are equal. To fix it, simply use <=
instead of <
(everywhere).
Upvotes: 2
Reputation: 181
Your code looks a bit complicated.
int Minimum(int first, int second, int third) {
int min = first;
if (second < min) {
min = second;
}
if (third < min) {
min = third;
}
return min;
}
This looks creepy, but it should do it.
Hope it helps to understand.
Upvotes: 2
Reputation: 201497
You have to return in your final else
block. But you could simplify your code with Math.min(int, int)
. Something like,
public static int Minimum(int first, int second, int third) {
return Math.min(first, Math.min(second, third));
}
Upvotes: 1