2013-04-16 111 views
8

這可能是最簡單的事情之一,但我沒有看到我做錯了什麼。爲什麼nextLine()返回一個空字符串?

我的輸入包含一個帶有數字的第一行(要讀取的行數),一堆帶有數據的行以及只有\ n的最後一行。我應該處理這個輸入,並在最後一行之後,做一些工作。

我有這個輸入:

5 
test1 
test2 
test3 
test4 
test5 
     /*this is a \n*/ 

以及讀取輸入我有這樣的代碼。

int numberRegisters; 
String line; 

Scanner readInput = new Scanner(System.in); 

numberRegisters = readInput.nextInt(); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 

我的問題是爲什麼我不打印任何東西?程序讀取第一行,然後什麼都不做。

+0

btw,不是第一個數字是測試的數量? – RiaD

+0

嘗試用行!= null替換!line.isEmpty()? – user2147970

+0

是的,它是測試次數 – Favolas

回答

31

nextInt不會讀取以下換行符,因此第一個nextLinewhich returns the rest of the current line)將始終返回一個空字符串。

這應該工作:

numberRegisters = readInput.nextInt(); 
readInput.nextLine(); 
while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 

但我的建議是不要用nextInt/nextDouble/next /等,因爲任何人都試圖保持代碼(包括你自己)可能不知道的,或混合nextLine已經忘記了,上面的,所以可能會被上面的代碼弄糊塗了。

所以我建議:

numberRegisters = Integer.parseInt(readInput.nextLine()); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 
+0

該死! 。爲什麼會出現這種行爲的解釋? –

1

我想我以前已經看到這個問題。我認爲你需要添加另一個readInput.nextLine()否則你只是在5結束之間讀書,之後

int numberRegisters; 
String line; 

Scanner readInput = new Scanner(System.in); 

numberRegisters = readInput.nextInt(); 
readInput.nextLine(); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 
0

\n其實它並不能完全回答這個問題(爲什麼你的代碼是不是工作),但你可以使用下面的代碼。

int n = Integer.parseInt(readInput.readLine()); 
for(int i = 0; i < n; ++i) { 
    String line = readInput().readLine(); 
    // use line here 
} 

對於我來說,更具可讀性,甚至可能(在文件的結尾有額外的信息)

BTW節省您的時間在這種罕見的情況下,當測試用例是不正確的,看來你參加一些編程競爭。請注意,該掃描儀輸入大量數據的速度可能會很慢。你可能會考慮使用BufferedReader可能StringTokenizer(在這項任務中不需要)

相關問題