此代码用于基本食品计算器的按钮。当我按下按钮时,输入对话框会显示您输入商品价格的位置。我遇到的问题是我无法弄清楚如何获得do ... while
循环以使输入对话框在输入后弹出。
我希望它总是回来,除非用户选择ok,什么都没有,或取消,在这种情况下循环应该中断并填充剩余的框。使用当前代码,我必须按下按钮,每次手动重新启动对话框。我一直在玩不同的条件和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();
答案 0 :(得分:2)
您在while语句中添加了一个条件。如果条件为真,它将继续迭代。
String s = "";
do
{
s = (String)JOptionPane.showInputDialog("Enter item price:");
if (s == null || s.equals(""))
{
...
}
...
}while(s != null || !s.equals(""));
答案 1 :(得分:1)
这可能会更好看为while
?
String s;
while ((s = (String) JOptionPane.showInputDialog("Enter item price:")) != null) {
if (s.isEmpty()) { break; }
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);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "You must enter numeric data only!");
}
}
double subtotal = getPurchase();
double total;
tax = subtotal * .065;
txtTax.setText(numForm.format(tax));
total = tax + subtotal;
txtTotal.setText(numForm.format(total));
这样,最终执行的代码以可视方式显示。
答案 2 :(得分:0)
do {
String s = (String)JOptionPane.showInputDialog("Enter item price:");
//user has pressed the cancel button then s becomes null
if(s == null){
break;
}
// your code
}
while(true);