[英]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.