我正在尝试重构我的代码,并尽可能添加方法。当我从方法读取文件并返回计算结果时,代码会陷入极度内存消耗、无限循环。
我的修改如下:
import java.util.Scanner;
public class NumberOfLines {
public static int compute () {
// read this file
String theFile = "numbers.txt";
Scanner fileRead = null;
if (NumberOfLines.class.getResourceAsStream(theFile) != null) {
fileRead = new Scanner(NumberOfLines.class.getResourceAsStream(theFile));
}
else {
System.out.print("The file " + theFile + " was not found");
System.exit(0);
}
System.out.println("Checkpoint: I am stuck here");
// count number of lines
int totalLines = 0;
while(fileRead.hasNextInt()) {
totalLines++;
}
fileRead.close();
return totalLines;
}
public static void main (String[] args) {
System.out.println("The total number of lines is: " + compute());
}
}
如果不是编写方法,而是将代码放在 main 上,那么它就可以工作。为什么是这样?
编辑
numbers.txt 的内容是:
5
2
7
4
9
1
5
9
69
5
2
5
6
10
23
5
36
5
2
8
9
6
所以我期望输出是:
总行数为:22
最佳答案
您陷入无限循环的原因是您正在读取文件,但没有在 while 循环中增加扫描仪 token 。所以 while 条件始终为真。
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}
关于java - 从方法读取文件时出现无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921171/