我怎样才能使用字母" S"来启动网格数组。在coordenate(1,1)?
public class Generator {
private static int row = 5;
private static int col = 5;
private static String[][] grid = new String[row][col];
public static void Grid_Generator() {
String AB = "_W";
SecureRandom rnd = new SecureRandom();
for (int i = 0; i < grid.length; i++) {
StringBuilder sb = new StringBuilder(row);
for (int j = 0; j < grid[i].length; j++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
sb.toString();
grid[i][j] = sb.toString();
}
}
}
任何帮助都会被贬低。
答案 0 :(得分:0)
尝试在grid
声明后立即添加此代码:
static {
grid[1][1] = "S";
}
上面的内容称为 static initialization block
,并且在创建grid
后立即加载类时运行(因为grid
也是静态的,它也会在加载类时设置。)
无论如何,您应该注意Java中的所有数组都以索引0
开头,而不是1
,因此设置grid[1][1]
等于"S"
会给你一个像这样的矩阵(grid[1][1] = "S";
):
[ ] [ ] [ ] [ ] [ ]
[ ] [S] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
...
不是这样的矩阵(grid[0][0] = "S";
):
[S] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
...
在旁注中,您在sb.toString();
方法中呼叫GridGenerator()
。这没什么,所以我从下面删除它。 :/
无论如何,在根据我建议的更改修改您的代码后,您应该知道:
public class Generator {
private static int row = 5;
private static int col = 5;
private static String[][] grid = new String[row][col];
static {
grid[1][1] = "S";
}
public static void Grid_Generator() {
String AB = "_W";
SecureRandom rnd = new SecureRandom();
for (int i = 0; i < grid.length; i++) {
StringBuilder sb = new StringBuilder(row);
for (int j = 0; j < grid[i].length; j++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
grid[i][j] = sb.toString();
}
}
}