3 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
這會(huì)起作用。我希望你能理解解決方案。如果解析失敗則 Integer.parseInt()拋出。NumberFormatException
void test() {
while (true) {
int aNumber;
try {
aNumber = Integer.parseInt(br.readLine());
System.out.println("Hurray you enterd a number! It is " + aNumber + ".");
return;
} catch (NumberFormatException | IOException e) {
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的代碼不起作用,因?yàn)檩斎胱址虺?之外的任何其他類型int都會(huì)生成 aNumberFormatException并且您沒有捕獲它。
if 語句是不必要的,因?yàn)橹挥薪o出文本時(shí)才會(huì)執(zhí)行 catch 塊。轉(zhuǎn)換時(shí)將引發(fā)異常,因此下面的行將不會(huì)執(zhí)行。
請檢查此代碼
void Test() {
while (true) {
try {
aNumber = Integer.parseInt(br.readLine());
System.out.println("Hurray you enterd a number! It is " + aNumber + ".");
return;
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以做的最簡單的事情就是捕獲NumberFormatException然后打印您想要的消息。
請參閱下面的工作示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadNumber {
public static void main(String[] args) {
int aNumber = 0;
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
aNumber = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
System.out.println("That wasn't a number.");
continue;
} catch (IOException e) {
e.printStackTrace();
}
if (aNumber >= 1) {
System.out.println("Hurray you entered a number! It is " + aNumber + ".");
continue;
} else {
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}
}
添加回答
舉報(bào)