Problem with return of a Java method

6

This method is giving problem in return. An error message with the following statement missing return statement is appearing. Could someone tell me a solution?

public String adicionar (String nome) {
    if(getNumLugares() < getNumDePassageiros())
        nomes.add(nome);
    else 
        return "Não ha lugares para mais passageiros";
 }
    
asked by anonymous 29.10.2017 / 04:55

2 answers

12

Your method, due to if , has two possible paths for execution to follow.

  • 1st path, if condition is true

    if(getNumLugares() < getNumDePassageiros())
        nomes.add(nome);
    
  • 2nd path, if the condition is false

    return "Não ha lugares para mais passageiros";
    

A method whose signature indicates that it should return a value must use the word return to end the path in all possible paths.

In your code, the error happens because on the 1st path the return was not used.

Change, to include return .

public String adicionar (String nome) {
    if(getNumLugares() < getNumDePassageiros()){
        nomes.add(nome);
        return "Adicionado"; //"Adicionado" ou outra coisa qualquer
    }
    return "Não há lugares para mais passageiros";
}

    

29.10.2017 / 12:13
8

The error:

  

missing return statement

Or in free translation:

  

missing return statement

Occurs when a method is declared with return and there are possibilities that this return value will not be reached.

In your case the method is declared with the return of a String ( public String adicionar (String nome) { ) and in its else this return is being respected. However, in% with_% there is no return, that is, when the if condition is executed no getNumLugares() < getNumDePassageiros() happens, disrespecting the declaration.

The way to solve your problem, roughly speaking, is to add the return statement to return , which can be done as follows:

public String adicionar(String nome) {
  if (getNumLugares() < getNumDePassageiros()) {
    nomes.add(nome);
    return nome;
  } else {
    return "Não há lugares para mais passageiros";
  }
}

But it is important to note that everything depends on how your method is executed, which may require that the return be done differently. You can return a status:

return "Passageiro adicionado.";

You can return null if there is no comment:

return null;

Or, as in the example, return the passenger name added:

return nome;

Perhaps in your case it is interesting to break the method in more parts, with a validation returning a id , however it is as it was said previously: It depends on the application that will be given to the method.     

29.10.2017 / 05:01