Infinite loop with an if within one of in Java

1

Good evening. I am doing a college job about an ATM and I have a small question. I am creating a do to make the replay menu of the ATM, but before the user enters the box, it will set a value for the accounts, because the balance variable is set to 0. After this, it will be released to the menu. But after setting the value, it keeps repeating the "teste" message. I would like some help.

Here is the code:

do{
           if(saldoCC<=0 && saldoCP<=0) {
               System.out.println("-----------------------------------------------------------");
               System.out.println("Saldo zerado em ambas as contas!");
               System.out.println("Para utilizar o caixa eletrônico sete o valor!");
               System.out.println("-----------------------------------------------------------");
               System.out.println("DIGITE O VALOR PARA REPOR O SALDO");
               System.out.println("-----------------------------------------------------------");
               System.out.print("Saldo da CONTA CORRENTE: R$");
               saldoCC = teclado.nextFloat();
               System.out.print("Saldo da CONTA POUPANÇA: R$");
               saldoCP = teclado.nextFloat();

               System.out.println("-----------------------------------------------------------");
               System.out.println("SALDO SETADO!");
               System.out.println("Conta Corrente: R$"+ saldoCC);
               System.out.println("Conta Poupança: R$"+ saldoCP);                  
           }else{
            System.out.println("teste");
           } 


        }while(op != 3);
    
asked by anonymous 22.04.2018 / 08:04

1 answer

2

Note that it will repeat the loop while op is other than 3. Within the loop, nowhere does it change the op variable. Therefore, assuming that op is 3, then after at least one of the saldoCC or saldoCP values is set to something greater than zero, the resulting loop would look like this:

do {
    if (condição sempre falsa) {
        // não importa mais
    } else {
        System.out.println("teste");
    }
} while (condição sempre verdadeira);

What's equivalent to this:

do {
    System.out.println("teste");
} while (true);

To fix this, I'm not exactly sure what you would do, because it depends on information that goes beyond what you posted in the question, especially how you expect to get or change the value of op . But some of the possible solutions would be:

  • Put a break; statement somewhere.

  • Put a op = 3; statement somewhere.

  • Put a return; statement somewhere.

  • Throw an exception somewhere.

  • Remove the loop do .

22.04.2018 / 09:28