Reputation: 89
Hello I have a quick question about multiple return statements vs single return statement at the end of the code.
From the first code, used return statement for every if, else if, and else statments and it gave me an error. And I thought I covered every possible cases but it game me an error bellow.
ERROR : missing return statement line:16
What causes this error? Also, are there any way that I can improve my second code?
public int caughtSpeeding(int speed, boolean isBirthday) {
if (!isBirthday)
if (speed <= 60)
return 0;
else if (speed <= 80)
return 1;
else
return 2;
if (isBirthday)
if (speed <= 65)
return 0;
else if (speed <= 85)
return 1;
else
return 2;
}
From this second code, I was able to get rid of the error.
public int caughtSpeeding(int speed, boolean isBirthday) {
int flag = 0;
if (!isBirthday)
if (speed <= 60)
flag = 0;
else if (speed <= 80)
flag = 1;
else
flag = 2;
if (isBirthday)
if (speed <= 65)
flag = 0;
else if (speed <= 85)
flag = 1;
else
flag = 2;
return flag;
}
Upvotes: 1
Views: 128
Reputation: 381
Well, it's sort-of obvious to us that one if "if birthday" and "if not birthday" is going to be executed, but the Java compiler doesn't see it that way.
To it, if the first 'if' does not get executed, and the second 'if' also does not get executed, then you come to the end of the method without executing a 'return'.
Upvotes: 2
Reputation: 546183
In your first code you test isBirthday
and !isBirthday
. Java isn’t smart enough to see that this list is exhaustive. And you wouldn’t normally write it like that, anyway: you’d write else
instead.
public int caughtSpeeding(int speed, boolean isBirthday) {
if (!isBirthday) {
if (speed <= 60)
return 0;
else if (speed <= 80)
return 1;
else
return 2;
} else {
if (speed <= 65)
return 0;
else if (speed <= 85)
return 1;
else
return 2;
}
}
Also, are there any way that I can improve my second code?
Yes: by using the first code. The second code uses a completely redundant variable. Use the first code.
In fact, because the second code uses a variable, Java won’t warn you if you forget a case — it will silently return 0
, because that’s how flag
was initialised. That would be a bug. When possible, write code that can’t lead to bugs but triggers compile errors instead — that’s what code 1 does, hence the error message (which was a false positive in this case, but which is in general correct).
Upvotes: 2