這段try catch語句問題出在哪?為什么會死循環(huán)不停輸出 "請輸入整數(shù)類型的id!"
while(true){ ????try?{ ????????id2?=?console.nextInt(); ????}catch?(InputMismatchException?ime){ ????????System.out.println("請輸入整數(shù)類型的id!"); ????????continue; ????} ????break; }
while(true){ ????try?{ ????????id2?=?console.nextInt(); ????}catch?(InputMismatchException?ime){ ????????System.out.println("請輸入整數(shù)類型的id!"); ????????continue; ????} ????break; }
2018-02-22
舉報
2019-11-18
經(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)容。
2018-02-22
經(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();
即:
把Scanner里不要的內(nèi)容吞掉,這樣Scanner才會進一步讀取后面的內(nèi)容。