为什么这段代码会触发无限循环?

时间:2011-03-20 15:13:05

标签: java infinite-loop

我正在编写一些简单的代码来解析文件并返回行数但是eclipse中的小红框不会消失所以我假设我触发了一个无限循环。我正在阅读的文本文件只有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;
    }           
}

2 个答案:

答案 0 :(得分:6)

你没有在while循环中调用s.nextLine()

应该是:

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

          }

答案 1 :(得分:1)

您只需检查循环中的hasNextLine。这将检查是否存在另一条线但未读取它。接下来是nextLine,您的代码就可以使用。

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