Search code examples
javainputmismatchexception

InputMismatch exception reading boolean values


I have a file with some values in it:

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

I need to read those values into a 2D ArrayList. The fist two values (11 and 8) would be the number of rows and columns respectively. So here is the code:

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

The problem is - the program reads first two numbers successfully, and when it comes to boolean values, it throws InputMismatch exception on line

buffer = scanner.nextBoolean();

so I can't undersand why. 0 should be read next and it is boolean - so what's actually mismatching?

I also point out that if change buffer type to integer and then assign scanner.nextInt(), the program would read all the values properly, so in the output I would see all of them. So then of course, I can change ArrayList to Integer to make that work, but it would be semantically wrong as it would hold only boolean values. Can anyone help me to find out the problem?


Solution

  • In your code you have this statement:

    buffer = scanner.nextBoolean();

    But I do not see boolean values true or false in the input file.

    In Java, 0 and 1 are not treated as boolean values like in other languages such as C.

    You need to read these values as int and then manually map them to boolean values.

    Logic something like this:

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