hughdavies
hughdavies

Reputation: 21

Missing return statement error in Java if-then tree

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

Answers (6)

acostache
acostache

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 elses to make it more efficient in this case).

Upvotes: 0

NPE
NPE

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

sbyd
sbyd

Reputation: 242

You need a return statement in case no if statement is true.

Upvotes: 0

Rohit Jain
Rohit Jain

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.

  • You can either make your if's an if-else if block, and then add an else at the end, and return some value from there.
  • Or, you can simply add a return statement at the end of your method.

Upvotes: 1

Juvanis
Juvanis

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

reprogrammer
reprogrammer

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

Related Questions