【问题标题】:Can't assign values to Player Object?无法为播放器对象赋值?
【发布时间】:2016-04-29 16:36:37
【问题描述】:

虽然我还是一个新手程序员,但在初始化对象方面我还是很有信心的。但是,我一生都无法弄清楚为什么我在这段代码中出现错误。有人可以帮我吗?行:玩家 player = new Players("Phil", [0][0] , false);是我出错的地方。

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;
}

}

【问题讨论】:

    标签: java arrays oop


    【解决方案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);
    

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

    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);
    

    【讨论】:

    • 我认为从长远来看,这可能是我想走的路。谢谢!
    【解决方案2】:

    编写静态 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] 用于初始化对象

    【讨论】:

    • 这是我一直在寻找的,但从更大的角度来看,另一个答案对我来说可能更容易。这是多么简单的疏忽。我可能应该在再次发帖之前先睡一觉!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2023-03-25
    • 2013-05-13
    • 1970-01-01
    相关资源
    最近更新 更多