Search and compare data

1

I need to perform a search and I created the following code to accomplish it, but without success. I wonder if I'm doing it the right way.

public void AcessoCC()
{
    int id = 0;
    Integer infoConta;


    System.out.println("Informe o número da conta: ");
    sc = new Scanner(System.in);
    infoConta = sc.nextInt();

   for(int i = 0; i < clienteCC.length; i++)
    {
        if (clienteCC[i].getNumConta() == infoConta)
        {
            id = i;
        }
    }

    if (clienteCC[id].getCliente() != null)
    {
        System.out.println("Cliente: " + clienteCC[id].getCliente());
        System.out.println("Conta número: " + clienteCC[id].getNumConta());
        System.out.println("Cliente: " + clienteCC[id].getSaldo());
        System.out.println("Limite Disponivel: " 
                + clienteCC[id].getLimite());
        System.out.println("Limite Disponivel: " 
                + clienteCC[id].getLimiteTotal());

        do
        {
            System.out.println("Deseja: 'S'aque, 'D'eposito, 'V'er saldo"
                    + " ou 'E'ncerrar");


        }while(op != 'T');
    }else
    {
        System.out.println("Dados não localizados");
    }
}
    
asked by anonymous 11.03.2016 / 10:08

1 answer

1

We have a little bug in your code!

But I do not know if this is what you would like to report!

What happens if the user enters an account that does not exist? It will always show the first!

You start the variable id with 0 , and this value is a valid position in a list!

If you do not find a Client, it will always show the first user in the list (position 0 of the list).

To fix, start the variable id with -1 ;

And before displaying the data, make sure id is different from -1 !

 int id = -1;

    ....
    if(id != -1){
          System.out.println("Cliente: " + clienteCC[id].getCliente());
            System.out.println("Conta número: " + clienteCC[id].getNumConta());
            System.out.println("Cliente: " + clienteCC[id].getSaldo());
            System.out.println("Limite Disponivel: " 
                    + clienteCC[id].getLimite());
            System.out.println("Limite Disponivel: " 
                    + clienteCC[id].getLimiteTotal());

            do
            {
                System.out.println("Deseja: 'S'aque, 'D'eposito, 'V'er saldo"
                        + " ou 'E'ncerrar");


            }while(op != 'T');

    }else{
       System.out.println("Dados não localizados");
    }

One more tip!

No need to iterate through the list! If you find the client, you can exit the iteration; To do this use the break;

Example:

 for(int i = 0; i < clienteCC.length; i++)
    {
        if (clienteCC[i].getNumConta() == infoConta)
        {
            id = i;
            break;
        }
    }
    
11.03.2016 / 12:52