此代码用于基本杂货计算器的按钮。当我按下按钮时,输入对话框会显示您输入商品价格的位置。我遇到的问题是,我无法弄清楚如何获得 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/