我对 Java 来说确实是全新的,我在代码中声明这个二维数组时遇到了麻烦。如果我这样做,我的代码将按预期工作:
class game{
String player = "x";
String[][] board = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
game(){
}
public void make_move(int square){
board[square/3][square%3] = player;
player = (player.equals("x")) ? "O" : "x";
}
那么在这种情况下,棋盘和玩家会是实例变量吗,因为我没有使用 static 关键字,然后游戏的每个实例都会有一个单独的棋盘和玩家?
来自 python,我习惯在构造函数内定义变量,并使用 self.whatever 等单词作为实例属性。所以我尝试在这里做同样的事情。
class game{
game(){
String[][] this.board = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
String this.player = "x";
}
public void make_move(int square){
board[square/3][square%3] = player;
player = (player.equals("x")) ? "O" : "x";
}
这根本不起作用,我收到了多个错误。 “此处不允许使用数组初始值设定项”和“无法解析符号 'player' ”。谁能告诉我这里发生了什么事并指出正确的方向?谢谢。
最佳答案
1:你说游戏和棋盘是实例变量是正确的。
2:您必须创建一个游戏对象才能实际使用 make_move 方法,因为它是一个非静态方法。您也不需要在 this.board 声明中使用此内容;简单地说 board=whatever 就可以了,因为它是一个实例变量。但是,必须在构造函数之前初始化这些实例变量,否则构造函数不知道它正在更改哪些变量。你可以做任何一个
class game {
String[][] board;
String player;
game() {
board = new String[][]{{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
player = "x";
}
public void make_move(int square) {
board[square / 3][square % 3] = player;
player = (player.equals("x")) ? "O" : "x";
} }
它使用构造函数来定义由类初始化的变量,或者更简单
class game {
String[][] board= new String[][]{{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
String player="x";
public void make_move(int square) {
board[square / 3][square % 3] = player;
player = (player.equals("x")) ? "O" : "x";
}}
如果您希望游戏的所有实例都具有相同的棋盘和玩家初始值(可能不是您想要的),它允许您跳过构造函数。将来,学习 java 作用域规则,并记住始终在类定义中定义实例变量,而不是构造函数。
关于java - 此处无法初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465485/