首页 > 解决方案 > Java - 为什么从文件读取时跳过零

问题描述

为什么我的程序在读取文件时会忽略零?例如,以下是文件中的数字:

0001 0011 0010

然后这是我的输出:

1
11
10

这是我的代码:

    File file = new File("num.txt");
    Scanner scanner = new Scanner(file);
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
        } else {
            scanner.next();
        }
    }

标签: javafile

解决方案


使用scanner.next()而不是scanner.nextInt().

使用scanner.nextInt()将删除任何前导零,因为 0001 == 1。


推荐阅读