从方法读取文件时获取无限循环



我正在尝试重构我的代码,并在可能的情况下添加方法。当我从方法中读取文件并返回计算结果时,代码将进入极端内存消耗,无限循环。

我的修改看起来像这样:

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 条件始终是正确的。

while (fileRead.hasNextInt()) {
    totalLines++;
    fileRead.nextInt();  // change made here only
}

最新更新