[英]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.