Javabat practice problem help

Shadow Conception

Golden Member
Mar 19, 2006
1,539
1
81
It's this.

Thus far, the code I've written is the following:

public int caughtSpeeding(int speed, boolean isBirthday)
{

if(speed <=60 || (speed <= 65 && isBirthday))
{
return 0;
}
if(speed >=61 && speed <=80 || (speed >= 66 && speed <= 86 && isBirthday))
{
return 1;
}
if(speed >= 81 || (speed >= 86 && isBirthday))
{
return 2;
}
}

However, I get the following error code after it refuses to compile: This method must return a result of type int.

I don't understand why it doesn't work. I'm returning integers ("return 0, return 1, return 2). Can anyone point me in the right direction?
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
The compiler wants you to put a return at the end of your function - it can't evaluate whether you've analyzed every possible case within your conditional statements.
Alternatively, you might want to use if, else if, else statements instead of your sequence of independent ifs.
 

Shadow Conception

Golden Member
Mar 19, 2006
1,539
1
81
Thanks a bunch! I made it follow an if-elseif-elseif pattern, as you suggested. At the very end of the code, I also added an "else return 3;", and Javabat indicates it's correct.
 

LumbergTech

Diamond Member
Sep 15, 2005
3,622
1
0
Originally posted by: Shadow Conception
Thanks a bunch! I made it follow an if-elseif-elseif pattern, as you suggested. At the very end of the code, I also added an "else return 3;", and Javabat indicates it's correct.

another alternative ..if you are sure that at least one of the cases will be true, is just to return the final case without checking

in this example...just return 2 if all of the other conditions fail

the ///else if part is just commenting it out for documentation purposes

public int caughtSpeeding(int speed, boolean isBirthday)
{

if(speed <=60 || (speed <= 65 && isBirthday))
{
return 0;
}else if(speed >=61 && speed <=80 || (speed >= 66 && speed <= 86 && isBirthday))
{
return 1;
}
//else if(speed >= 81 || (speed >= 86 && isBirthday))

return 2;
}