2016-04-29 17 views
1

私はまだ初心者プログラマーですが、オブジェクトの初期化についてはかなり自信があります。しかし、私はこのコードでエラーが発生する理由を理解することができません。誰かが私を助けてくれますか?ライン:Players players =新しいプレーヤー( "Phil"、[0] [0]、false);私はエラーが発生する場所です。Playerオブジェクトに値を割り当てることができませんか?

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

、あなたが作ることができます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); 
+0

私は長期的には、これは私が行きたいと思う方法だと思います。ありがとう! –

1

を:

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

intが[] [] は、宣言型のフォームです

new int [0] [0]はオブジェクトの初期化に使用されます

+0

これは私が探していたものですが、もう一つの答えはもっと大きな絵の中で私にとってより簡単かもしれません。どのような単純な見落としであるか。私はおそらく再び投稿する前にいくつかの睡眠を取得する必要があります!ありがとう! –

関連する問題