有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在循环catch语句时执行?

我正在制作一个带有“其他”选项的收银机,它允许用户通过用户输入添加金额。我使用JOptionPane完成了此操作,“其他”按钮代码如下所示:

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.");
        }       
}                         

这个while循环不会关闭JOptionPane,即使在输入数字时,如何正确地循环


共 (2) 个答案

  1. # 1 楼答案

    我建议您在代码中使用不同的方法:

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

    此代码将循环,直到用户输入有效数字,然后您可以在while循环之后使用。可能需要一些改进,如取消逻辑或第二次更改消息,但主要思想是这样的

  2. # 2 楼答案

    这个问题本身并不清楚。我假设,如果try部分没有按照您希望的方式运行,JOptionPane应该重新打开,并且应该提示用户再次执行该操作。如果是这样,您可以执行以下操作:

    创建一个方法:

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

    并调用操作中的方法:

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