java - 从方法读取文件时出现无限循环

标签 java file methods java.util.scanner infinite-loop

我正在尝试重构我的代码,并尽可能添加方法。当我从方法读取文件并返回计算结果时,代码会陷入极度内存消耗、无限循环。

我的修改如下:

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/

相关文章:

c++ - 之间有什么区别。和 -> 在 C++ 中调用方法

java - 函数重载: Terminology for different types of overloaded functions?

java - 使用java扫描仪读取文本文件

在 c 中使用 fseek 后核心转储

java - 如何为一个类(class)个性化 equals 并测试一组中的相等值?

java - switch 语句中的值范围

c - 读取失败的 C 程序

c# - GraphicsPath.IsClockWise() 扩展方法

java - Scala.Byte vs java.lang.Byte - 推荐使用哪个?

java - UcanAccess 中的 DELETE 函数抛出奇怪的异常