Zulfe
Zulfe

Reputation: 881

Data Failing to Transfer from File to Integer Array

So I'm really not sure how to put this to words. I'm having trouble transferring the data from a file my program has created back into the program for manipulation.

The program creates a .sp file consisting of 81 values 0-9. Here's what the file I'm using looks like:

000030640020698170085700003007010000090503060000060700800007290012489050054020000

The code I'm using to pull these values from the file to an integer array is:

JFileChooser chooser = new JFileChooser();
        int[][] puzzle = new int[9][9];
        chooser.setCurrentDirectory(new File("~/Documents"));
        int retrieval = chooser.showSaveDialog(null);
        if(retrieval == JFileChooser.APPROVE_OPTION){
            FileReader fr = null;
            try {
                fr = new FileReader(chooser.getSelectedFile());
            } catch (FileNotFoundException e){
                e.printStackTrace();
            }
            BufferedReader textReader = new BufferedReader(fr);
            String line = textReader.readLine();

            int pos = 0;
            for(int i = 0; i < 9; i++)
                for(int j = 0; j < 9; j++){
                    System.out.println("Putting " + line.charAt(pos) + " in (" + i + ", " + j + ")");
                    puzzle[i][j] = line.charAt(pos);
                    pos++;
                }

line prints out as:

000030640020698170085700003007010000090503060000060700800007290012489050054020000

I'm even getting output that makes sense...

Putting 0 in (0, 0)
Putting 0 in (0, 1)
Putting 0 in (0, 2)
Putting 0 in (0, 3)
Putting 3 in (0, 4)
Putting 0 in (0, 5)
Putting 6 in (0, 6)
Putting 4 in (0, 7)
Putting 0 in (0, 8)
Putting 0 in (1, 0)

However, when I view the newly created matrix, I get:

48 48 48 48 51 48 54 52 48 
48 50 48 54 57 56 49 55 48 
48 56 53 55 48 48 48 48 51 
48 48 55 48 49 48 48 48 48 
48 57 48 53 48 51 48 54 48 
48 48 48 48 54 48 55 48 48 
56 48 48 48 48 55 50 57 48 
48 49 50 52 56 57 48 53 48 
48 53 52 48 50 48 48 48 48 

Why is this happening? I don't see any errors, and the debugging sysout seems to prove it. Is the data somehow becoming corrupted?

Upvotes: 1

Views: 37

Answers (1)

TNT
TNT

Reputation: 2920

Look here:

puzzle[i][j] = line.charAt(pos);

charAt returns a char, not an int. When you store the char at a position in your array, the Unicode code point of the character is stored, and not the integer value that you expect.

This can be easily solved by using the Character class's getNumericValue method:

puzzle[i][j] = Character.getNumericValue(line.charAt(pos));

Upvotes: 2

Related Questions