-1

I keep getting a missing return statement error but I don't know where. Every time I follow the code, I feel at least one of the if statements provide the return statement.

Code:

public User[] getUsersContaining(String query) {
   User[]nameSearch = new User[this.capacity];

   if(nameSearch == null)
        return null;
   for (int i=0; i<this.capacity; i++){
       if(this.array[i].getName().contains(query)){
        nameSearch[i]=this.array[i];
        bubbleSort date2 = new bubbleSort();
        date2.bubblesort(nameSearch);
        return nameSearch;
       }
   }
}
adrianbanks
  • 81,306
  • 22
  • 176
  • 206
  • Ok, i think I understand what you mean. If i put a return statement at the end of the method will that mean that will be the final return value? When I return null at the end of the method the application gives an error so I don't know what to return otherwise. When i try an else return null after the if statement I still get the missing return statement error. Sorry I'm very new to programming. – user6036979 Mar 09 '16 at 00:33
  • if your function is meant to `get... ` something, you return what the function is meant to "get". Your function is called "getUsersContaining", so you should be returning the users that contain the string. – Carcigenicate Mar 09 '16 at 00:38
  • The error happens because if `this.capacity` == 0, and nameSearch != null, your function won't return anything, since it never enters the loop. – Carcigenicate Mar 09 '16 at 00:40

1 Answers1

3

A method which declares a return type must declare a return statement for every possible branch of flow of that method. Which means basically there is a flow of code possible in your method which does not end in a return statement (hint: what happens if your if statement returns false inside the loop every time? Eventually the loop will end and nothing will be returned.)

You can put a catch-all return statement at the bottom of your method doing something like returning null, or perhaps even throwing an Exception which will allow you to not "return anything"

Kon
  • 10,702
  • 6
  • 41
  • 58