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

发布于 2024-10-24 16:04:55 字数 904 浏览 3 评论 0原文

我正在编写一些简单的代码来解析文件并返回行数,但是 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;
    }           
}

I am writing some simple code to parse a file and return the number of lines but the little red box in eclipse won't go off so I assume I am triggering an infinite loop. Th Text file i am reading has only 10 lines...here's the code: What am I doing wrong?

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;
    }           
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放低过去 2024-10-31 16:04:55

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

应该是:

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

          }

You're not calling s.nextLine() in the while-loop:

should be:

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

          }
九命猫 2024-10-31 16:04:55

您只需在循环中检查 hasNextLine 即可。这会检查是否存在另一行,但不会读取它。让它跟在 nextLine 后面,您的代码就会正常工作。

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

You only check hasNextLine within your loop. This checks if another line is present but does not read it. Let it follow by nextLine and your code will work.

while(s.hasNextLine()){
    s.nextLine();
    noLines++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文