初始化2D数组 [英] Initialize 2D array
问题描述
我正在尝试初始化2D数组,其中每个元素的类型为 char . 到目前为止,我只能按照以下方式初始化此数组.
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';
}
}
我认为如果数组是10 * 10,这是简单的方法. 有什么有效的方法吗?
I think if the array is 10*10, it is the trivial way. Is there any efficient way to do that?
推荐答案
这样的事情如何?
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
以下完整的Java程序:
The following complete Java program:
class Test {
public static void main(String[] args) {
char[][] table = new char[3][3];
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
System.out.println (table[row][col]);
}
}
输出:
1
2
3
4
5
6
7
8
9
之所以可行,是因为Unicode中的数字是从\ u0030(这是从'0'
获得的)开始连续的.
This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0'
).
表达式'1' + row * 3 + col
(在0
和2
之间(在其中包括row
和col
的范围内进行变化))只是为您提供了从1
到9
的字符.
The expression '1' + row * 3 + col
(where you vary row
and col
between 0
and 2
inclusive) simply gives you a character from 1
to 9
.
很显然,如果您走得更远的话,它不会给您字符10
(因为它是两个字符),但是对于3x3情况来说,它仍然可以正常工作.您将不得不更改此时生成数组内容的方法,例如:
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 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:
String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
for (int col = 0; col < 5; col++)
table[row][col] = String.format("%d", row * 5 + col + 1);
这篇关于初始化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!