Hi! I initially tried solving this task by declaring an int variable "result", doing the comparisons and setting "result" equal to a/b/c depending on the comparison, and returning "result" at the end of the method. However, even though my code worked, the task wouldn't accept it. So I rewrote it to return a/b/c without the use of a middling variable.
if (a <= b) {
if (a <= c) {
return a;
}
else {
}
}
else {
if (b <= c) {
return b;
}
else {
return c;
}
}
}
}
However, Java got mad and said I wasn't returning a value. I'm not sure why???
I managed to bypass it this way, but it seems kinda sketchy.
if (a <= b) {
if (a <= c) {
return a;
}
else {
}
}
else {
if (b <= c) {
return b;
}
else {
}
}
return c;
}
}
Is there a better/more elegant/less janky way to write this? I'm okay with the logic behind coding, but still pretty bad at Java's syntax.
Kian Sun
Level 5
Returning values inside an if-else statement?
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Deepak Chandra
1 May 2019, 07:12
just remove those empty else blocks
and use else if statement
0
Junjun
26 April 2019, 00:15
I used this code based on the coding style SESE, (some useful reference):
The code below also works. It uses the Java ternary operator ? :
I prefer the code using if-else for its readability, but the code using the ternary operator is short and sweet.
+2
hidden #10440733
14 May 2019, 00:21
ternary worked good
0
Guadalupe Gagnon
24 April 2019, 17:36
In the first bit of code you shared the empty else block, if reached, would mean your code has a path that would not return a value, otherwise you had the right idea. If you combined the first two if statements into one using logical AND, then had two else statements (one an else-if) you can rewrite that code as:
As can be seen in my code above, you do not need to use curly brackets in if-else statements (and loops) AS LONG AS there is one and only one line of code to execute (A line of code ends in a semi-colon)
So code like this is acceptable:
Also you do not need to put else at the end of an if statement.
The second bit of code you shared is almost exactly the bit of code that I shared above, which was a rewrite of what you were trying to attempt in your first bit of code. In your code if none of your paths lead to a valid return, then 'c' is returned It can be re-written as such and still pass:
Notice from my two bits of code (which are yours just re-written), the only difference is one 'else'. +4
Kian Sun
25 April 2019, 02:30
*snaps vigorously* I totally forgot about and/or operators!! That makes so much more sense and streamlines everything.
Thank you for all the pointers on the brackets and syntax as well! It was super helpful.
+2