Reputation: 21
I'm trying to tell a Critter program to choose an attack type randomly from four options; I thought I had my return statement bases covered, but I'm getting a "missing return statement" error from drjava:
public Attack fight(String opponent) {
int fightChoice = new Random().nextInt(4);
if(fightChoice == 0){
return Attack.ROAR;
} if(fightChoice == 1){
return Attack.POUNCE;
} if(fightChoice == 2){
return Attack.SCRATCH;
} if(fightChoice == 3){
return Attack.FORFEIT;
}
}
any idea why that may be?
Upvotes: 2
Views: 2906
Reputation: 2275
The above/previous answers explain that you need a return
statement at the end, in case no if
is true. I would only like to add a suggestion, as a good practice (maybe not best) in this case: just return a result only at the end and assign a value for the returned result in each if
(maybe add some else
s to make it more efficient in this case).
Upvotes: 0
Reputation: 500673
Basically, the compiler is not smart enough to figure out that you've covered every possibility with the four if
statements (it doesn't really know about the contract on the return value of Random.nextInt()
).
You therefore need to add a dummy return
after the final if
. It doesn't really matter what you return there, since it's effectively dead code. However, it would be good style to return some sort of unused or clearly invalid value.
edit: On second thoughts, rather than return a dummy value, it would be better to unconditionally throw some kind of a "programmer error" exception.
Upvotes: 3
Reputation: 213311
Just think, what happens when none of your if condition
is true
? In that case, you would not be returning anything from that method.
You should return from every path your method can follow, else you will get missing return
statement error.
if's
an if-else if
block, and then add
an else
at the end, and return some value from there.Upvotes: 1
Reputation: 25950
You might think that your if statement's cover all possible cases but compiler just compiles the code, doesn't cover/calculate possibilities. You need to add return
statement after the last if-statement.
Upvotes: 1
Reputation: 14718
You need a missing statement outside the if statement. For instance, if flightChoice == 4
, none of the if
conditions will hold, so you should add a return
at the end of the method. This return statement has to return something of type Attack
like the if
branches.
Upvotes: 1