从文本文件中读取数字不起作用

Reading numbers from text file doesn't work

我正在尝试从下一个文件中读取数字并计算出文件中最大的数字,但是我得到的答案是错误的。该文件有一堆由 space 分隔的数字,一段时间后会生成一个新行。当我检查 max 的输出时,我可以看到它越来越小,这是不应该发生的,所以我认为这可能与仅比较当前行有关?我看到人们将数字添加到列表中,然后我可以订购它们并获取最后一个索引,但为什么这种方式不起作用?

int max = 0;
try (Scanner in = new Scanner(file)) {
    while (in.hasNextInt()) {
        if (in.nextInt() > max) {
            max = in.nextInt();
        }
    }
} catch (FileNotFoundException e) {
    System.out.println("File not found");
}
System.out.println(max);
if(in.nextInt() > max) {
    max = in.nextInt();
}

每次调用 nextInt() 方法时,您都会从文件中读取一个整数值,因此您最终会每隔一个整数就跳过一次。

试试这样的东西:

int value = in.nextInt();

if(value > max) {
    max = value;
}