像这样的东西怎么样:
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
以下完整的 Java 程序:
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'
)。
表达式'1' + row * 3 + col
(您在其中变化row
以及col
介于两者之间0
和2
包括在内)只是为您提供了一个从1
to的字符9
。
显然,如果你走得更远,这不会给你角色10
(因为那是两个角色),但它适用于 3x3 案例。此时您必须更改生成数组内容的方法,例如:
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);