[英]How do exit a while loop with a JOptionPane
我的代碼遇到問題,如果用戶單擊CANCEL.OPTION
或CLOSED.OPTION
則試圖退出此循環。 我處理了異常,但似乎無法使用窗口上的按鈕。 該程序從用戶的年齡輸入中獲取用戶的出生年份。 我遇到的問題是我無法通過按鈕結束循環。 提前致謝!
public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
try {
age = Integer.parseInt(enteredAge);
if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
System.out.println("MADE IT INTO IF");
}
age = year - age;
prompt = false;
showMessageDialog(null,age);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return age;
}
有幾個帶有不同參數的showInputDialog重載版本。 只有最新版本的Javadoc才能正確記錄用戶按下Cancel鍵時返回值為null的情況。
public int getBirthYear() {
boolean prompt = true;
while (prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
if (enteredAge == null) { // Cancel pressed
age = -1;
prompt = false;
} else {
try {
age = Integer.parseInt(enteredAge);
age = year - age;
prompt = false;
showMessageDialog(null, age);
} catch (NumberFormatException e) {
showMessageDialog(null, "Enter a valid number");
}
}
}
return age;
}
可能是您想對程序進行一些重組。 將年齡設為局部變量或其他任何變量。 將int
用於實數整數值。 Integer
是int的對象包裝器類。
您問題的最簡單答案是,只需在try and catch子句的外面放promp = false,它應該可以工作:
public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
try {
age = Integer.parseInt(enteredAge);
if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
System.out.println("MADE IT INTO IF");
}
age = year - age;
showMessageDialog(null,age);
} catch (NumberFormatException e) {
e.printStackTrace();
}
prompt = false;
}
return age;
}
問題出在范圍之內。 輸入的年齡並沒有使它進入捕獲塊。 我解決了這個問題。
public Integer getBirthYear() {
boolean prompt = true;
do {
try {
age = year - Integer.parseInt(showInputDialog(null,"Enter age:"));
prompt = false;
showMessageDialog(null, age);
} catch (NumberFormatException e) {
String ageEntered = showInputDialog(null,"Enter age:");
e.printStackTrace();
if(ageEntered == null) { //close the file if Cancel is chosen
prompt = false;
}
}
} while(prompt);
return age;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.