InputMismatch 异常读取布尔值

InputMismatch exception reading boolean values

我有一个包含一些值的文件:

11
8
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 1 1 1 1 1 1 0 0
0 1 1 0 1 1 1 0 1 1 0
1 1 1 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 0 1
1 0 1 0 0 0 0 0 1 0 1
0 0 0 1 1 0 1 1 0 0 0

我需要将这些值读入二维 ArrayList。前两个值(11 和 8)分别是行数和列数。所以这是代码:

            Scanner scanner = new Scanner(file);

            int x, y;

            x = scanner.nextInt();
            System.out.println(x + " has been read");

            y = scanner.nextInt();
            System.out.println(y + " has been read");


            ArrayList<ArrayList<Boolean>> pixelMap;
            pixelMap = new ArrayList<ArrayList<Boolean>>();
            ArrayList<Boolean> buffer_line = new ArrayList<Boolean>();

            Boolean buffer;


            for (int i = 0; i < x; i++){
                for (int j = 0; j < y; j++){
                    buffer = scanner.nextBoolean();
                    System.out.println(buffer + " has been read");
                    //buffer_line.add(buffer);
                }
                //pixelMap.add(buffer_line);
                //buffer_line.clear();
            }

问题是 - 程序成功读取了前两个数字,当涉及到布尔值时,它在

行抛出 InputMismatch 异常
buffer = scanner.nextBoolean();

所以我不明白为什么。 0 接下来应该读取,它是布尔值 - 那么实际上不匹配的是什么?

我还指出,如果将 buffer 类型更改为整数,然后分配 scanner.nextInt(),程序将正确读取所有值,因此在输出中我会看到所有这些值。那么当然,我可以将 ArrayList 更改为 Integer 以使其工作,但这在语义上是错误的,因为它只包含布尔值。 谁能帮我找出问题所在?

在您的代码中有这样的语句:

buffer = scanner.nextBoolean();

但我在输入文件中没有看到 booleantruefalse

在 Java 中,0 和 1 不像在其他语言(例如 C)中那样被视为布尔值。

您需要将这些值读取为 int,然后手动将它们映射到 boolean 值。

逻辑是这样的:

int val = scanner.nextInt();
boolean buffer = (val == 1) ? true : false;