Infinite loop with an if inside a do in Java

Asked

Viewed 144 times

1

Good evening. I’m doing a college job on an ATM and I’m having a little doubt. I’m creating a do to make the ATM repeat menu, 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 cashier menu. But after setting the value the value it keeps repeating the message "teste". I’d like some help.

Here’s 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);

1 answer

2


Notice that he will repeat the loop while op is different from 3. Inside the loop, nowhere it changes the variable op. So, supposing that op is 3, then after at least one of the values saldoCC or saldoCP be set with 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 is equivalent to this:

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

To fix this, I don’t know exactly what you would do because it depends on information that goes beyond what you posted in the question, in particular how you expect to get or change the value of op. But some of the possible solutions would be:

  • Place an instruction break; somewhere.

  • Place an instruction op = 3; somewhere.

  • Place an instruction return; somewhere.

  • Throw some exception somewhere.

  • Untie do.

  • Good afternoon! thanks for the help, I put a break; after System.out.println("test"); and it worked! this repeating as I wanted!

Browser other questions tagged

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