2012-10-25 71 views
2

可能重複:
Scanner issue when using nextLine after nextInt掃描儀對象表現不同爲整數VS字符串輸入

在下面的兩個代碼段,我首先請求的所需要輸入的數目而讓用戶輸入特定類型的許多輸入。當所需的輸入是字符串類型時,除非我先使用s.next(),否則它會減少一個輸入,而對於整數,它工作正常。我不明白爲什麼。有人能解釋一下嗎?由於

首先代碼字符串輸入和nextLine功能:

public static void main(String args[]){ 

    Scanner s = new Scanner(System.in); 

    int num = s.nextInt(); 

    String[] inputs = new String[num]; 

    for (int i = 0; i < inputs.length; i++) { 
     inputs[i]=s.nextLine(); 
    } 
    System.out.println("end of code"); 
} 

第二碼使用整數投入和nextInt功能:

public static void main(String args[]){ 

    Scanner s = new Scanner(System.in); 

    int num = s.nextInt(); 

    Integer[] inputs = new Integer[num]; 

    for (int i = 0; i < inputs.length; i++) { 
     inputs[i]=s.nextInt(); 
    } 
    System.out.println("end of code"); 
} 
+2

**相關問題:[使用nextLine後nextInt掃描儀問題](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint)。 –

+0

呃...我沒有看到第一個: - \ –

回答

0

這是因爲下面一行:

int num = s.nextInt(); 

你的下一個INT只返回INT直到它到達\ n字符。

如果你有一個測試文件是這樣的:

4 
1 
2 
3 
4 

你的字符代碼如下所示:

4'\n' 
1'\n' 
2'\n' 
3'\n' 
4'\n' 

所以,當你抓住整數,它會搶了4爲貴「 nextInt()「方法在掃描儀上。當你告訴它抓取下一行「nextLine()」時,它將獲取該行的其餘部分,該行只是'\ n',並且不會將任何值存儲到數組中的第一個值中。在反面,如果你告訴它抓取下一個整數「nextInt()」,它將搜索直到它找到下一個整數,這將導致1進入數組的第一個值。