我正在做與處理異常相關的練習。在使用Scanner類和以下練習來檢查InputMismatchExceptions時,我從下面的代碼中得到以下結果。錯誤:在連續使用掃描儀類中加入整數
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter an integer: ");
int a = getInt();
System.out.print("Enter a second integer: ");
int b = getInt();
int result = a + b;
System.out.println(result);
}
public static int getInt(){
while (true){
try {
return sc.nextInt();
}
catch(InputMismatchException e){
System.out.print("I'm sorry, that's not an integer."
+ " Please try again: ");
sc.next();
}
}
}
產量爲:
Enter an integer: 2 3
Enter a second integer: 5
看來,如果nextInt的第一通話()我輸入「2 3」,或兩個整數與下一次它們之間的空間,即nextInt()被調用,它接收到前兩個加在一起的整數,然後暫停程序。這裏究竟發生了什麼?
P.S.有沒有人有我的提示,以更好的方式格式化我的代碼,並使其更適合其他編碼人員閱讀?
看看[此](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next -nextint-or-other-nextfoo-methods)適用。 –
我看了,我不認爲它適用。不管怎麼說,多謝拉。 –