0

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
3
  • A character like '3' is represented as the "integer" value 51. Google ASCII code, and so on. Commented Aug 5, 2015 at 4:40
  • Use Integer.valueof(String) Commented Aug 5, 2015 at 4:40
  • Better: use a char[3][3]. Commented Aug 5, 2015 at 4:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.