tav*_*ndo 2 java methods file infinite-loop java.util.scanner
I am trying to refactor my code, and adding methods where possible. When I read a file from a method and return the result of the computation, the code goes into extreme memory consumption, infinite loop.
My modification looks like this:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
If instead of writing the method, and placing the code on main, then it works. Why is this?
EDIT
Contents of numbers.txt is:
5
2
7
4
9
1
5
9
69
5
2
5
6
10
23
5
36
5
2
8
9
6
Run Code Online (Sandbox Code Playgroud)
So I expect out put to be:
总行数为:22
陷入无限循环的原因是,您正在读取文件,但没有在while循环中增加扫描程序令牌。因此,while 条件始终为真。
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |