从方法读取文件时出现无限循环
Getting infinite loop when reading file from method
我正在尝试重构我的代码,并尽可能添加方法。当我从方法中读取文件并 return 计算结果时,代码进入极端内存消耗,无限循环。
我的修改是这样的:
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 循环中递增扫描仪令牌。所以 while condition 总是 true.
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}
我正在尝试重构我的代码,并尽可能添加方法。当我从方法中读取文件并 return 计算结果时,代码进入极端内存消耗,无限循环。
我的修改是这样的:
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 循环中递增扫描仪令牌。所以 while condition 总是 true.
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}