2015-08-25 30 views
0

我試圖做到這一點:錯誤採取輸入字符串整數之後在java中

int n = myScanner.nextInt(); 
for(int i=0;i<n;i++){ 
    String str = myScanner.nextLine(); 
    . 
    . 
    . 
} 

當我編譯它顯示了一些錯誤java.util.Scanner.nextInt(Scanner.java:2117)。 最初我認爲這是nextLine()的問題,所以我使用next()。後來我發現,如果我走輸入的N即

int n = myScanner.nextInt(); 
    myScanner.nextLine(); 

然後它好工作之後添加myScanner.nextLine()。我想知道爲什麼會發生這種情況?

+3

在http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo看看 - 方法的解釋。 – Codebender

+0

@Codebender我訪問了上面的鏈接。在解決方案中,異常處理是在使用Integer.parseInt()時完成的,但是當我使用parseInt時,它不會拋出任何異常。爲什麼這樣? – hermit

+0

@hermit,只有在無法解析的情況下才會拋出NumberFormatException異常。但是'NumberFormatExcetion'是一個** unchecked **(擴展的RuntimeException)異常,因此您不必明確地寫入拋出或處理它(儘管如果您不拋出它將拋出)。希望這是明確的。 – Codebender

回答

2

需要消耗經過整數,當你進入換行符:

int n = myScanner.nextInt(); //gets only integers, no newline 
myScanner.nextLine(); //reads the newline 
String str; 
for(int i=0;i<n;i++){ 
    str = myScanner.nextLine(); //reads the next input with newline 
    . 
    . 
    . 
} 
1

有一個換行符離開流。通過@moffeltje使用代碼或可能嘗試這個辦法:

int n = Integer.parseInt(myScanner.nextLine()); 
for(int i=0;i<n;i++){ 
    String str = myScanner.nextLine(); 
    . 
    . 
    . 
} 
+0

如果您要使用此方法,則必須處理NumberFormatException,因爲parseInt會嘗試將換行符解析爲整數值 – hermit

+0

@hermit,'Scanner.nextLine()'將**消耗**新行字符,但它不會被返回給調用者。所以換行符不會被解析。 – Codebender

+0

@Codebender謝謝,解決了混淆 – hermit