简体   繁体   English

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

[英]Reading numbers from text file doesn't work

I'm trying to read numbers from a next file and figure out the biggest number in the file however I've been getting the wrong answer.我正在尝试从下一个文件中读取数字并找出文件中的最大数字,但是我得到了错误的答案。 The file has a bunch of numbers seperated by a space and after a while a new line is made.该文件有一堆由空格分隔的数字,一段时间后会生成一个新行。 When I check my output of max I can see it getting smaller and larger which shouldn't be happening so I think maybe it's something to do with only comparing the current line?当我检查我的max output 时,我可以看到它越来越小,这是不应该发生的,所以我认为这可能与仅比较当前行有关? I've seen that people add the numbers to a list and then I could order them and grab the last index but why doesn't this way work?我已经看到人们将数字添加到列表中,然后我可以对它们进行排序并获取最后一个索引,但为什么这种方式不起作用?

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();
}

Every time you invoke the nextInt() method you read an integer value from the file, so you end up skipping every second integer.每次调用 nextInt() 方法时,您都会从文件中读取 integer 值,因此您最终会每隔一秒跳过 integer。

Try something like:尝试类似:

int value = in.nextInt();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM