第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

正在回答

2 回答


經(jīng)過本人網(wǎng)上查詢,發(fā)現(xiàn)原因如下:
java.util.Scanner在獲取下一個單詞時,如果要求得到的輸入跟實際的輸入格式不匹配(例如要數(shù)字但實際輸入不是數(shù)字),則會拋出InputMismatchException,并且輸入流的內(nèi)容不會被吞掉。
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("請輸入整數(shù)類型的id!");
????????continue;
????}
????break;
}
把Scanner里不要的內(nèi)容吞掉,這樣Scanner才會進一步讀取后面的內(nèi)容。

0 回復(fù) 有任何疑惑可以回復(fù)我~

經(jīng)過本人網(wǎng)上查詢,發(fā)現(xiàn)原因如下:

java.util.Scanner在獲取下一個單詞時,如果要求得到的輸入跟實際的輸入格式不匹配(例如要數(shù)字但實際輸入不是數(shù)字),則會拋出InputMismatchException,并且輸入流的內(nèi)容不會被吞掉。
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("請輸入整數(shù)類型的id!");
????????continue;
????}
????break;
}

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

5 回復(fù) 有任何疑惑可以回復(fù)我~

舉報

0/150
提交
取消

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

我要回答 關(guān)注問題
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號