亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

這段try catch語句問題出在哪?為什么會死循環不停輸出 "請輸入整數類型的id!"

while(true){
????try?{
????????id2?=?console.nextInt();
????}catch?(InputMismatchException?ime){
????????System.out.println("請輸入整數類型的id!");
????????continue;
????}
????break;
}

正在回答

2 回答


經過本人網上查詢,發現原因如下:
java.util.Scanner在獲取下一個單詞時,如果要求得到的輸入跟實際的輸入格式不匹配(例如要數字但實際輸入不是數字),則會拋出InputMismatchException,并且輸入流的內容不會被吞掉。
java.util.Scanner的JavaDoc說得很清楚:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
可以在代碼的catch中添加一行:
String token = console.next();
即:
1
2
3
4
5
6
7
8
9
10
while(true){
????try?{
????????id2?=?console.nextInt();
????}catch?(InputMismatchException?ime){
????????String?token?=?console.next();??//添加此處代碼!
????????System.out.println("請輸入整數類型的id!");
????????continue;
????}
????break;
}
把Scanner里不要的內容吞掉,這樣Scanner才會進一步讀取后面的內容。

0 回復 有任何疑惑可以回復我~

經過本人網上查詢,發現原因如下:

java.util.Scanner在獲取下一個單詞時,如果要求得到的輸入跟實際的輸入格式不匹配(例如要數字但實際輸入不是數字),則會拋出InputMismatchException,并且輸入流的內容不會被吞掉。
java.util.Scanner的JavaDoc說得很清楚:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

可以在代碼的catch中添加一行:

String token = console.next();

即:

while(true){
????try?{
????????id2?=?console.nextInt();
????}catch?(InputMismatchException?ime){
????????String?token?=?console.next();??//添加此處代碼!
????????System.out.println("請輸入整數類型的id!");
????????continue;
????}
????break;
}

把Scanner里不要的內容吞掉,這樣Scanner才會進一步讀取后面的內容。

5 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

這段try catch語句問題出在哪?為什么會死循環不停輸出 "請輸入整數類型的id!"

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號