2015-05-31 30 views
0

我正在做與處理異常相關的練習。在使用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.有沒有人有我的提示,以更好的方式格式化我的代碼,並使其更適合其他編碼人員閱讀?

+1

看看[此](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next -nextint-or-other-nextfoo-methods)適用。 –

+0

我看了,我不認爲它適用。不管怎麼說,多謝拉。 –

回答

1

當您輸入「2 3」(兩個整數之間有一個空格)時,scanner.nextInt()將拉入2並將3仍留在掃描儀中。現在,當下一個nextInt()被調用時,它將拉入剩下的3,而用戶不必再輸入數據。

您可以通過使用nextLine()來解決此問題,並檢查輸入字符串是否不包含空格。

像這樣:

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 { 
      String input = sc.nextLine(); 
      if (!input.contains(" ")) { 
       int integer = Integer.parseInt(input); 
       return integer; 
      } else { 
       throw new InputMismatchException(); 
      } 
     } catch (InputMismatchException | NumberFormatException e) { 
      System.out.print("I'm sorry, that's not an integer. Please try again: "); 
     } 
    } 
} 

結果:

Enter an integer: 2 3 
I'm sorry, that's not an integer. Please try again: 2 
Enter a second integer: 3 
5 
+0

謝謝!這工作。但是,我添加了另一個catch語句,以便將信件輸入到nextLine()而不是數字中: –

+0

catch(NumberFormatException d) –

+0

@AdamOdell好的......請參閱我的更新。 – Shar1er80