无法在此处初始化数组

时间:2018-11-25 07:25:33

标签: java arrays

我实际上是Java的新手,我在代码中声明此2d数组时遇到了麻烦。如果这样做,我的代码将按预期工作:

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关键字,因此board和player是实例变量吗?然后每个游戏实例将有一个单独的board和player?

来自python,我习惯于在构造函数中定义变量,并使用诸如self.what之类的词作为实例属性。所以我试图在这里做同样的事情。

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'”。谁能告诉我这是怎么回事,并指出正确的方向吗?谢谢。

2 个答案:

答案 0 :(得分:2)

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范围规则,并记住始终在类定义而不是构造函数中定义实例变量。

答案 1 :(得分:1)

class Game{
String player;
String[][] board = null;

 Game(String playerName){ 
     this.player = playerName; 
     this.board = new String[][]{{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}}`
 }

 public void makeMove(int square){
     board[square/3][square%3] = player;
     player = (player.equals("x")) ? "O" : "x";

 }

您需要了解来自Python的Java变量范围的概念。很好的起点:https://www.geeksforgeeks.org/variable-scope-in-java/

Game(){
         String[][] this.board = new String[][]{{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
         String this.player = "x";
     }

您在此处定义的玩家变量和棋盘变量存在于此函数的范围内,并且在函数执行完成后将被删除,除非您返回该值。

由于构造函数不返回变量,因此必须在类级别声明该变量,并在需要时在构造函数中对其进行初始化。