Suman Palikhe
Suman Palikhe

Reputation: 357

creating a 2d array from a String

I am trying to create a 2d array from a String. But i am getting some weird results when i try to set the value of elements in the array. Here String s = 120453678;

public int[][] create2D(String s){
    int[][] puzzle = new int[3][3];
    int a;

    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){

            puzzle[i][j] = (int)s.charAt(i*3+j);
            System.out.println(s.charAt(i*3+j));                
            System.out.println(i +"  "+ j+"  "+ puzzle[i][j]);
        }
    }

    return puzzle;      

}

The output i am getting is. Don't know why its 49, 50 , 51 and so on

 1
0  0  49
2
0  1  50
3
0  2  51
4
1  0  52
5
1  1  53
0
1  2  48
6
2  0  54
7
2  1  55
8
2  2  56

Upvotes: 0

Views: 63

Answers (1)

Aakash
Aakash

Reputation: 2109

You are converting the character to it's int representation. That's why you are getting this result.

puzzle[i][j] = (int)s.charAt(i*3+j);

ASCII table can be referred below. You can see that 49 is ASCII value of character '1'.

http://www.asciitable.com/

To fix your code, you can use

puzzle[i][j] = Character.getNumericValue(s.charAt(i*3+j));

Upvotes: 2

Related Questions