[英]How do I while-loop a catch statement?
我正在制作带有“其他”选项的收银机,它允许用户通过用户输入添加金额。 我使用 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.");
}
}
这个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
循环后使用。 可能需要一些改进,例如取消逻辑或第二次更改消息,但主要思想是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.