简体   繁体   中英

How do I while-loop a catch statement?

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?

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();
}

I suggest you a different approach in your code:

  String prijs = "";
  double overigePrijs = -1;
  while (true) {
     prijs = JOptionPane.showInputDialog(null, "Vul een bedrag in");
     if (prijs != null) { // if user cancel the return will be null
        try {
           overigePrijs = Double.parseDouble(prijs);
           break; // Exits the loop because you have a valid number
        } catch (NumberFormatException ex) {
           // Do nothing
        }
     } else {
        // You can cancel here
     }
     // You can send a message to the user here about the invalid input
  }

  if (overigePrijs > 0) {
     aantalProducten[6]++;
     totaalPerProduct[6] += overigePrijs;
  }
  huidigePrijsDisplay();

This code will loop until the user enters a valid number and then you can use after the while loop. Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM