What do I need to change in this method to work properly?

Asked

Viewed 54 times

0

This method searches, by the Customer’s phone, the Reservations that are made in it.

The Customer may have more than one reservation, but the method is only showing the first reservation registered to the customer. What should I change in the code to show them all?

public void pesquisaImovelPorCliente(String telefoneCliente)
{
    boolean localizouImovel = false;//variável auxiliar para verificar se a busca teve sucesso

    for(int i = 0; i< qtdeReservas; i++)
    {
        if(ListaDeReservas[i].cliente.getTelefone().equals(telefoneCliente)){

            ListaDeReservas[i].exibeDados();

            //busca teve sucesso-
            localizouImovel = true;

            break;
        }
    }

    if(!localizouImovel)//se não localizou
      System.out.println ("Não foi localizado nenhuma acomodação para este telefone.");
}
  • 2

    After seeing the correct answer, if you can change the question title. This will help users who may have the same problem as you in the future.

2 answers

4

Avoid using flags as much as possible, every time you have a flag in a code it is probably misspelled. In this case it would be better to do the following.

public void pesquisaImovelPorCliente(String telefoneCliente) {
    for (int i = 0; i< qtdeReservas; i++) {
        if (ListaDeReservas[i].cliente.getTelefone().equals(telefoneCliente)) {
            ListaDeReservas[i].exibeDados();
        } else {
            System.out.println ("Não foi localizado nenhuma acomodação para este telefone.");
            break;
        }
    }
}

Have cases that eliminate the flag can make the code more confusing.

I put in the Github for future reference.

  • Thanks for the tip!

3


That one break is making the flow out of the for. Eliminate it!

  • It was faster than me =)

  • It worked perfectly, thank you very much!

Browser other questions tagged

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