我想用Scanner接收一個整型輸入,并在出現輸入非整型情況時拋出異常提示,同時要求用戶重新輸入,用了如下代碼:import java.util.Scanner;public class HelloWorld{? ? public static void main(String[] args){? ? ? ? int i = 0;? ? ? ? Scanner sc = new Scanner(System.in);? ? ? ? System.out.println("請輸入數量:");? ? ? ? while(true) {? ? ? ? ? ? try {? ? ? ? ? ? ? ? i = sc.nextInt();? ? ? ? ? ? ? ? System.out.println("i="+i);? ? ? ? ? ? ? ? break;? ? ? ? ? ? } catch(Exception e) {? ? ? ? ? ? ? ? System.out.println("請輸入一個整型數字:");? ? ? ? ? ? }? ? ? ? }? ? }}執行如下:請輸入數量:a請輸入一個整型數字:請輸入一個整型數字:請輸入一個整型數字:……在接收到一個非法輸入a時,程序重復不斷拋出異常提示“請輸入一個整型數字:”,而不能中斷接收新的輸入,請問這是為什么,錯在哪里?
4 回答

慕娘4410084
TA貢獻1條經驗 獲得超2個贊
while (true) {
try {
id1 = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("請輸入整數型的ID:");
sc.next();// 讀取下一個值,如果不加這條語句,控制臺得到的還是你上次輸入的數,再一次進入catch語句,所以會一直循環報錯
}
}

viva_la_vida
TA貢獻1條經驗 獲得超0個贊
sc .nextInt() 只會在找到匹配之后 才會 向前移動,因此每一次匹配仍然會在當前的輸入之中進行匹配
具體可以查看:
String java.util.Scanner.next(Pattern pattern)
Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.
添加回答
舉報
0/150
提交
取消