-1

Please, when I try to run my main class, I get an error telling me that I am missing a return statement for the following code, however i have used a return statement. I am new to Java so kindly explain.

public boolean addPassenger(Person a){
       for(int i =0; i < passengers.length; i++){
         if(passengers[i]==null){
           passengers[i]=a;
           NumOfPassengers++;
           return true;
         }
         else
           return false;
       }

     }
FredPeter
  • 1
  • 5
  • Why use a loop for this? Just do `if (passengers.length > 0 && passengers[0] == null) {... return true;} else {return false;}` – fabian Sep 25 '16 at 13:09
  • If it's empty, I wanna insert the input a into that slot in the array @fabian – FredPeter Sep 25 '16 at 14:08
  • This is not what your code would be doing, however, since in the first iteration there's a `return` statement which prevents any other iterations from running. – fabian Sep 25 '16 at 15:50

1 Answers1

0

You need to have a return statement for every possible valid path through the code. In your case, you are missing a return statement for the case where passengers.length == 0.

Joe C
  • 15,324
  • 8
  • 38
  • 50