2011-03-20 52 views
0

我正在寫一些簡單的代碼來解析文件並返回行數,但eclipse中的紅色小方塊不會熄滅,所以我假設我正在觸發無限循環。 Th我正在閱讀的文本文件只有10行...這是代碼:我做錯了什麼?爲什麼此代碼觸發無限循環?

import java.io.*; 
import java.util.Scanner; 
public class TestParse {  
    private int noLines = 0;  
    public static void main (String[]args) throws IOException { 
     Scanner defaultFR = new Scanner (new FileReader ("C:\\workspace\\Recommender\\src\\IMDBTop10.txt")); 
     TestParse demo = new TestParse(); 
     demo.nLines (defaultFR); 
     int x = demo.getNoLines(); 
     System.out.println (x); 
    } 
    public TestParse() throws IOException 
    { 
     noLines = 0; 
    } 
    public void nLines (Scanner s) { 
     try { 
      while (s.hasNextLine()) 
       noLines++; 
     } 
     finally { 
       if (s!=null) s.close(); 
     } 
    } 
    public int getNoLines() { 
     return noLines; 
    }   
} 

回答

6

你不是要求在while循環s.nextLine()

應該是:

 while(s.hasNextLine()){ 
      s.nextLine(); // <<< 
      noLines++; 

      } 
+0

非常感謝很多!...一點睡眠剝奪,這是一個相當愚蠢的省略...再次感謝! – algorithmicCoder 2011-03-20 15:19:43

1

你只是你的循環中檢查hasNextLine。這將檢查是否存在另一行但不讀取它。讓它跟着nextLine,你的代碼將工作。

while(s.hasNextLine()){ 
    s.nextLine(); 
    noLines++; 
}