2016-04-29 67 views
1

雖然我仍然是一個新手程序員,但在初始化對象時我相當有信心。然而,我不能爲了我的生活找出爲什麼我在這段代碼中出現錯誤。有人可以幫我嗎?該線:球員球員=新球員(「菲爾」,[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; 
} 

}

回答

1

[0][0]無效語法。改爲使用new int[0][0]

您試圖使用2維數組來表示位置。


它可能是最好使用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); 
+0

從長遠來看,我認爲這可能是我想要走的路。謝謝! –

1

正確的方式來寫你的靜態無效的主要是:

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

INT [] [] 是聲明的形式,它只是將對象聲明爲int a例如

new int [0] [0]用於初始化對象

+0

這就是我一直在尋找的東西,但其他答案可能會更容易讓我在大路上走下去。這是多麼簡單的監督。我應該再次張貼之前睡一覺!謝謝! –