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); 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. Use new int[0][0]
instead.
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:
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:
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:
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
new int[0][0] is used to initialize the object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.