2016-04-29 135 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

这就是我一直在寻找的东西,但其他答案可能会更容易让我在大路上走下去。这是多么简单的监督。我应该再次张贴之前睡一觉!谢谢! –