Incorrect data output in the list

Asked

Viewed 38 times

-1

Hello, the following method is not showing the data output correctly. At the end of the run it shows the name of the product and then the message "CPF not registered". Follows an image to facilitate understanding.

   public void consultarCompra(){

   System.out.println("INFORME SEU CPF: ");
    String cpf = entrada.next();

    for (int i = 0; i < dados.size(); i++) {
        if (dados.get(i).cpf.equals(cpf)) {
            System.out.println("O DONO DESTE CPF COMPROU: \n" + dados.get(i).nome);

    } else {
        System.out.println("CPF NÃO ENCONTRADO");

    }
}

} inserir a descrição da imagem aqui

  • If you have one more item on that list that CPF 123 did not buy, the "CPF NOT FOUND" will appear once again. Now think...

1 answer

0

In the way you have programmed for each item on the list that has not purchased something you print "CPF NOT FOUND". The correct thing to do would be to use a solution called a flag, which consists of creating a variable with a false value, and if a "certain thing" happens inside the FOR, it switches to true to be able to use this information outside the repetition loop.

Look at the solution:

public void consultarCompra(){

    boolean comprouAlgo = false;
    for (int i = 0; i < dados.size(); i++) {

        if (dados.get(i).equals(cpf)) {
            System.out.println("O DONO DESTE CPF COMPROU: \n" + dados.get(i));
            comprouAlgo = true;
        }
    }
    if (!comprouAlgo) {
        System.out.println("CPF NÃO ENCONTRADO");
    }
}

Browser other questions tagged

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