简体   繁体   English

我如何while循环一个catch语句?

[英]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:我使用 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.");
        }       
}                         

This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?这个while循环不会关闭JOptionPane,即使在输入数字时,我该如何正确循环?

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.我假设如果try部分没有按您的意愿运行, JOptionPane应该重新打开,并且应该提示用户再次执行。 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.此代码将循环直到用户输入有效数字,然后您可以在while循环后使用。 Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.可能需要一些改进,例如取消逻辑或第二次更改消息,但主要思想是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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