Search code examples
javaif-statementwhile-loopjoptionpane

How do I emplement a loop to get the program to ask the user for input again instead of ending the program


ans = JOptionPane.showInputDialog(null, "Enter amount to be withdrawn from checking");
double withCheck = Double.parseDouble (ans);
if (withCheck >= checking)
    {
    JOptionPane.showMessageDialog(null, "You do not have enough in your account for that.");
    }
else
    {
    double sum = checking - withCheck;
    JOptionPane.showMessageDialog(null, "Your checking balance is now: $" + sum + ", and your savings balance is: $" + savings);
    }
}

Currently this code ends the program when withCheck >= checking, I would like to know of a way to use a loop of some sort to ask the question again until the "if" statement is false and can continue to the else statement.


Solution

  • Just add a while loop with true condition and break it upon some condition getting true.

    While(true)
    {
        ans = JOptionPane.showInputDialog(null, "Enter amount to be withdrawn from checking");
        double withCheck = Double.parseDouble (ans);
        if (withCheck >= checking)
            {
            JOptionPane.showMessageDialog(null, "You do not have enough in your account for that.");
            }
        else
            {
            double sum = checking - withCheck;
            JOptionPane.showMessageDialog(null, "Your checking balance is now: $" + sum + ", and your savings balance is: $" + savings);
            break;
            }
        }
    }