无法为Player Object分配值?

时间:2016-04-29 16:36:38

标签: java arrays oop

虽然我还是一名新手程序员,但在初始化对象时我相当自信。但是,我不能为我的生活找出为什么我在这段代码中得到错误。有人可以帮帮我吗?线:玩家玩家=新玩家(“菲尔”,[0] [0],假);是我收到错误的地方。

public class Players {
private String player;
private int [][] position;
private boolean turn;
public static void main(String[]args){
    Players player = new Players("Phil", [0][0] , false);
}
public Players(String player, int[][] position, boolean turn){
    this.player = player;
    this.position = position;
    this.turn = turn;
}
public String getPlayer(){
    return player;
}
public void setPlayer(String player){
    this.player = player;
}
public int [][] getPosition(){
    return position;
}
public void setPosition(int [][] position){
    this.position = position;
}
public boolean getTurn(){
    return turn;
}
public void setTurn(boolean turn){
    this.turn = turn;
}

}

2 个答案:

答案 0 :(得分:1)

[0][0]是无效的语法。请改用new int[0][0]

您尝试使用二维数组来表示某个位置。

使用2个整数代表你的位置可能会更好:

public class Players {
    private String player;
    private int x, y; // <---
    private boolean turn;
    ...
    public Players(String player, int x, int y, boolean turn){
        this.player = player;
        this.x = x;
        this.y = y;
        this.turn = turn;
    }
    ...
}

创建一个玩家:

Player player = new Players("Phil", 0, 0, false);

或者,您可以创建一个表示2D空间坐标的类:

public class Coordinate {
    public final int x, y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class player {
    ...
    private Coordinate position;
    ...
    public Players(String player, Coordinate position, boolean turn){
        this.player = player;
        this.position = position;
        this.turn = turn;
    }   
    ...
}

然后创建一个播放器:

Player player = new Players("Phil", new Coordinate(0, 0), false);

答案 1 :(得分:1)

编写静态void main的正确方法是:

public static void main(String[]args) {
        Players player = new Players("Phil", new int[0][0] , false);
}
  

INT [] []   是一个声明形式,它只是将对象声明为int a例如

     

new int [0] [0]用于初始化对象

相关问题