【发布时间】:2019-07-07 10:08:34
【问题描述】:
我正在尝试重构我的代码,并在可能的情况下添加方法。当我从方法中读取文件并返回计算结果时,代码进入了极端的内存消耗,无限循环。
我的修改如下:
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 循环中添加
System.out.println(fileRead.next())以检查您正在阅读的内容。查看它是否与文本文件匹配。 -
你是对的。有用。我错过了 while 循环的中断。谢谢。
标签: java file methods java.util.scanner infinite-loop