javawhile-loopjframejoptionpane

How do I keep asking the user for input if the input wasn't a number?


I'm making a cash register with an "other" option, which allows the user to add an amount through user input. I have done this with a JOptionPane, the "other" button code is the following:

private void btnOverigActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String prijs  = JOptionPane.showInputDialog(this, "Vul een bedrag in");
    try {
        double overigePrijs = Double.parseDouble(prijs);
        if (overigePrijs > 0){
            aantalProducten[6]++;
            totaalPerProduct[6] += overigePrijs;
        }
        huidigePrijsDisplay();
    }
    
    catch (Exception letter){
        while (true){
        prijs = JOptionPane.showInputDialog(this, "Vul a.u.b. alleen cijfers in.");
        }       
}                         

This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?


Edit after almost finishing my SE studies: I was missing an if-statement in my while-loop. What I was trying to do was checking if the input of prijs were only numbers and if not, keep showing the dialog. I never got around to fixing this because it's an old project but I should have stated the motivation behind the code more clearly!


Solution

  • The question is not clear itself. What I assume that if the try part does not run as you wish, the JOptionPane should reopen and user should be prompted to do it again. If it is so, you can do the following:

    Create a method:

    private void doTheTask(){
    String prijs  = JOptionPane.showInputDialog(this, "Vul een bedrag in");
      try{
      //your task here.
    }
    catch (Exception letter){
      //Call the method again.
      doTheTask();
    }
    }
    

    And call the method inside your action:

    private void btnOverigActionPerformed(java.awt.event.ActionEvent evt){
        doTheTask();
    }