InputMismatch异常读取布尔值

时间:2015-11-08 22:44:05

标签: java inputmismatchexception

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

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

我需要将这些值读入2D 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以使其工作,但它在语义上是错误的,因为它只包含布尔值。 任何人都可以帮我找出问题吗?

1 个答案:

答案 0 :(得分:1)

在您的代码中,您有以下声明:

  

buffer = scanner.nextBoolean();

但我在输入文件中看不到booleantruefalse

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

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

逻辑是这样的:

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