簡體   English   中英

無法為播放器對象分配值?

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

雖然我仍然是新手程序員,但是在初始化對象時我還是很有信心的。 但是,我無法終生弄清楚為什么在此代碼中出現錯誤。 有人可以幫我嗎? 這行代碼:Players 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;
}

}

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

編寫靜態void main的正確方法是:

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

int [] []是聲明性形式,它只是將對象聲明為int例如

新的int [0] [0]用於初始化對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM