Stop the loop when you find a result

Asked

Viewed 116 times

1

public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            return null;
        } else {                
            return id;
        }                   
    }
}

this is the code, it’s returning the id or null repeatedly. how do I stop the loop when I find the result and only return one result instead of several?

  • You can use it break when you find the result.

  • 2

    This code makes no sense and if it is repeating the problem is in the method call busca. Note that this will run only once always. In the first interaction, it will fall into one of the two blocks of the if and in both there is a return terminating the method.

1 answer

3


Let’s see your code:

public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            return null;
        } else {                
            return id;
        }                   
    }
}

When it starts iterating the first element, if the name matches the expected one, it returns null, and when it does not match returns this object.

This is not right. It always returns in the first iteration! Moreover, it only returns the first element if it nay is what you’re looking for. If it’s what you’re looking for it doesn’t return anything! It makes no sense.

I think what you wanted is this:

public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            // Achou o que queria, retorna.
            return id;
        }                   
    }
    return null; // Tentou todos e não achou nenhum, desiste.
}

As suggested by Felipe Fonseca in a comment, it is worth treating nulls and avoid NullPointerExceptions:

public Objeto busca(String nome){
    Objects.requireNonNull(nome, "O nome do objeto a buscar deve ser informado.");
    for(Objeto id : MinhaLista){
        if(nome.equals(id.getNome())){
            // Achou o que queria, retorna.
            return id;
        }                   
    }
    return null; // Tentou todos e não achou nenhum, desiste.
}

I’m assuming that MinhaLista contains no elements null because it doesn’t usually make sense. If it does, you can add a if (id == null) continue; before this other if which is already in the code.

  • 2

    It is worth adding a treatment to Nullpointer in the code to avoid unwanted exceptions

  • @Felipefonseca Ok, edited. Thank you very much. :)

  • I am grateful for the help. positively.

  • @Josemaximilian Thanks, thank you! Also positive you. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.