java - do while 循环问题

标签 java loops while-loop do-while

此代码用于基本杂货计算器的按钮。当我按下按钮时,输入对话框会显示您输入商品价格的位置。我遇到的问题是,我无法弄清楚如何获得 do ... while 循环来使输入对话框在输入后弹出。

我希望它始终能够恢复,除非用户选择“确定”或“取消”,在这种情况下,循环应该中断并填充剩余的框。使用当前代码,我每次都必须按下按钮才能手动恢复对话框。我一直在尝试不同的 while 条件和 if 语句,但我似乎无法让它工作。我是初学者,如果这很简单,我很抱歉,感谢您的宝贵时间。

注意:我故意将 while 条件留空,只是表明这就是我需要它的地方。

  NumberFormat numForm = NumberFormat.getCurrencyInstance();
  double itemPrice;
  double tax;

  do {
    String s = (String)JOptionPane.showInputDialog("Enter item price:");
    if (s == null || s.equals("")) { 
        double subtotal = getPurchase();
        double total;
        tax = subtotal * .065;
        txtTax.setText(numForm.format(tax));
        total = tax + subtotal;
        txtTotal.setText(numForm.format(total));
    } else {
        try {
            itemPrice = Double.parseDouble (s);
            recordPurchase(itemPrice);
            txtPrice.setText(numForm.format(itemPrice));

            double subtotal = getPurchase();     

            txtSubtotal.setText(numForm.format(subtotal));
            int items = getItems();
            String totalItems = Integer.toString(items);
            txtItems.setText(totalItems);

        } // end try
        catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "You must enter numeric data only!");
        } // end catch
      } // end if Else
    }// end do
    while();

最佳答案

您在 while 语句中添加了一个条件。如果条件为真,它将继续迭代。

String s = "";
do 
{
    s = (String)JOptionPane.showInputDialog("Enter item price:");
    if (s == null || s.equals("")) 
    {
        ...
    }
    ...
}while(s != null || !s.equals(""));

关于java - do while 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20205316/

相关文章:

c - 如何在 C 中以特定速率运行循环(在仿真中)

r - 如何查看列表的任何元素是否仅包含 R 中的某个值

java - 如何获得 try/catch 语句的正确输出?

java - 如何从一个地方的纬度和经度得到一个地方到另一个地方的方向?

Java:方法中的枚举参数

javascript - Jquery 循环无法正常工作?

javascript - 在 while 循环中使用 if 语句

java - SwingWorker 中的进度对话框

ruby - 将值插入到 YAML 转储的哈希中

java - bufferedreader - 读入 stringbuffer 而不是 string