#code that calculates the smallest of three numbers. Rewrite: instead of ? and : use if else
1 messages · Page 1 of 1 (latest)
its interesting that u ask this way around
usually people know if-else very well and have to learn ?: first
and not the other way around
Foo foo = condition ? A : B;
is the same as
Foo foo;
if (condition) {
foo = A;
} else {
foo = B;
}
🙂
it was the solution within the course but I never once saw that in the previous lessons but that´s the way the course is built sometimes you need something before it even gets discussed in the exercises
its called the ternary operator and it does exactly what i just showed 🙂
"if condition, use this. else that"
Drink drink = isItHot() ? iceTea : hotTea;
I set on that exercise two hours and tied to solve it with if else before I looked into the solution and there were those two symbols used which I like I already metioned never saw before 😂
I see so instead of return I should use a letter
but there are a few conditions how can I describe those with just one condition bracket
I feel like I went through all possible if else combinations within those two hours and after I attempted to rewrite the given solution
awesome 😂 seems like I elegantly went around all those possibilities haha
well. step back and try to first write the explicit solution. dont try to be overly clever on it
when is a the min element? when it is smaller than b and c
if (a < b && a < c) {
return a;
}
there u go, first case
I tried that as well
but it ended in a error case one sec I think I still have it copied somewhere
then understand and fix the error instead of throwing the code away and trying a totally different approach 🙂
u must have made a minor mistake only
I tried to fix it several times but it said something about enum etc
if u have the code still, we can take a look
if (a < b && a < c){
return a;
}
else if (b < a && b < c){
return b;
}
else{
return c;
}
}
It worked now will definetely take your advice to heart and try to stick to my one solution and try to figure it out until it gets accepted and not until I don´t understand the error message
Thanks a bunch! @tepid torrent
what happens if a = b < c
you mean a < b <c ?
no
if a and b are equal, and less than c
but right now your method returns c
<*
which is wrong
public class Solution {
public static int min(int a, int b, int c) {
//schreib hier deinen Code
if (a <= b && a <= c){
return a;
}
else if (b <= a && b <= c){
return b;
}
else{
return c;
}
now the system verified it with all the given conditions only cliqued run and not verify
thanls for bringing that part to my attention
@scenic tartan