我如何 while-loop 一个 catch 语句?

How do I while-loop a catch statement?

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

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,即使在输入数字时,我该如何正确循环呢?

问题本身并不清楚。我假设如果 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();
}

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

  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循环之后使用了。可能需要进行一些改进,例如取消逻辑或第二次更改消息,但主要思想是这样。