I am trying to initialize a 2D array, in which the type of each element is char.
So far, I can only initialize this array in the follow way.
public class ticTacToe
{
private char[][] table;
public ticTacToe()
{
table[0][0] = '1';
table[0][1] = '2';
table[0][2] = '3';
table[1][0] = '4';
table[1][1] = '5';
table[1][2] = '6';
table[2][0] = '7';
table[2][1] = '8';
table[2][2] = '9';
}
}
I think if the array is 10*10, it is the trivial way.
Is there any efficient way to do that?
How about something like this:
The following complete Java program:
outputs:
This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from
'0').The expression
'1' + row * 3 + col(where you varyrowandcolbetween0and2inclusive) simply gives you a character from1to9.Obviously, this won’t give you the character
10(since that’s two characters) if you go further but it works just fine for the 3×3 case. You would have to change the method of generating the array contents at that point such as with something like: