gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:40:39 25 4
gpt4 key购买 nike

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

最佳答案

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

应该是:

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

}

关于java - 为什么这段代码会触发无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com