2017-03-28 14 views
0

基本上,我試圖計算一個txt文件中有多少行,然後將它作爲索引存儲到數組中。爲什麼當我在java文件io中使用.hasNext時,計數器會繼續計數

File file = new java.io.File("number.txt"); 
Scanner s = new Scanner(file); 
int count = 0; 
while(s.hasNextLine()) 
{  
    count++; 
    System.out.println(count); 
} 
System.out.println("There is: " + count + " line); 
int[] array = new int[count]; 

不過,我認識到「計數」去無窮,它從來沒有停止計數,但我只在我的txt文件20行。這是爲什麼發生?

注:我知道如何解決,但我只是好奇,爲什麼它繼續計數

+10

因爲你從來沒有讓'Scanner'移到下一行通過's.nextLine()'... – Zircon

+1

直到你閱讀它時,該行仍然存在。 –

+1

「我知道如何修復」,那麼如何修復它?你如何看待修復工作? – Pshemo

回答

4

您應該使用

scanner.nextLine() 

結合

scanner.hasNextLine() 

hasNextLine將檢查有下一行可用或不可用,但它不會轉到下一行,因爲您需要使用nextLine。當它們都被使用時,你會在解析最後一行後看到計數器停止。所以你的代碼應該是這樣的

File file = new java.io.File("number.txt"); 
Scanner s = new Scanner(file); 
int count = 0; 
while(s.hasNextLine()) 
{ 
    s.nextLine(); 
    count++; 
    System.out.println(count); 
} 
System.out.println("There is: " + count + " line); 
int[] array = new int[count]; 
0

因爲這是它的設計方式。

公共布爾hasNextLine()

返回true,如果有在此掃描器輸入另一條線。 此方法可能會在等待輸入時阻塞。掃描儀不會通過任何輸入前進 。

返回: 真當且僅當此掃描器有輸入的另一行 大段引用

拋出: IllegalStateException - 如果此掃描器已關閉

+0

這就是爲什麼當我在while循環中聲明一個變量var = s.nextInt()時,它會轉到下一行,但沒有它,它會一直保留在文件的第一行? – WordSide

+0

是的,正如上面提到的javadoc,hasNexLine()不會超過任何輸入,但nextInt()會(或至少嘗試)。 – ndlu

相關問題