简体   繁体   English

无法为播放器对象分配值?

[英]Can't assign values to Player Object?

While I am still a novice programmer, I am fairly confident when it comes to initializing objects. 虽然我仍然是新手程序员,但是在初始化对象时我还是很有信心的。 However, I cannot for the life of me figure out why I get an error in this code. 但是,我无法终生弄清楚为什么在此代码中出现错误。 Could someone help me out? 有人可以帮我吗? the line: Players player = new Players("Phil", [0][0] , false); 这行代码:Players player = new Players(“ Phil”,[0] [0],false); is where I get an error. 是我得到错误的地方。

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

} }

The [0][0] is not valid syntax. [0][0]是无效的语法。 Use new int[0][0] instead. 改用new int[0][0]

You're trying to use a 2 dimensional array to represent a position. 您正在尝试使用二维数组来表示位置。


It would probably be better to use 2 integers to represent your position: 使用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;
    }
    ...
}

And create a player with: 并创建具有以下内容的播放器:

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

Alternatively, you could make a class that represents coordinates in 2D space: 或者,您可以创建一个表示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;
    }   
    ...
}

Then create a player with: 然后使用以下方法创建一个播放器:

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

The correct way to write your static void main is: 编写静态void main的正确方法是:

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

int[][] is a declarative form, it just declare the object as int a for example int [] []是声明性形式,它只是将对象声明为int例如

new int[0][0] is used to initialize the object 新的int [0] [0]用于初始化对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM