2017-11-28 3 views
0

私は使用しているコンストラクタに問題があります。基本的には、最初のxとyの位置(コードの2番目のブロック)を適切なコンストラクタに渡す2つのWaterDropコンストラクトがあります。問題は、int x、yインスタンス変数を適切な開始位置に設定しないことです。最初のコンストラクタを適切に設定しますが、2番目のコンストラクタを使用して点を描画するときには、自動的に(0、0)の位置に設定されます。とにかく最初のコンストラクタを呼び出すことができるので、xとyの位置を適切な開始位置に設定しますか?Javaマルチコンストラクタ設定の問題

public class WaterDrop 
{ 
// instance variables - replace the example below with your own 
private int x; 
private int y; 
private int xVelocity; 
private int yVelocity; 
private DrawingPanel panel; 
private static int DIAMETER = 1; 
private int delayStart; 
private int bounceLimit; 

private static Random rand = new Random(); 

public WaterDrop(int x, int y){ 
    this.x = x; //**These assign just fine but I can't get them to get passed** 
    this.y = y; //**into the next WaterDrop constructor** 
       //**i.e. (200, 400)** 

} 

public WaterDrop(DrawingPanel panel, boolean move) 
{ 
    //initialise instance variables //**In this constructor they are still** 
            //**initialized to 0** 
    this.panel = panel; //**Since they are initialized at 0, when I draw the** 
         //**waterDrops they appear at the location (0, 0)** 

} 

    xVelocity = rand.nextInt(3) - 1; 
    yVelocity = rand.nextInt(20) + 1 ; 
    delayStart = rand.nextInt(100); 
    bounceLimit = 0; 

} 

これは私がWaterFountainクラスからで渡しているものです:

public class WaterFountain{ 
.... 

public WaterFountain(DrawingPanel panel, int xLocation, int yLocation) 
{ 
    this.panel = panel; 
    this.xLocation = xLocation; 
    this.yLocation = yLocation; 

    for(int i = 0; i < NUM_WATER_DROPS; i++){ 
     waterDrop[i] = new WaterDrop(this.xLocation, this.yLocation); 
    } 
} 


.... 
} 
+0

をどのようにあなたは何*「適切な出発の場所を知っているだろうし、あなたが最初のコンストラクタを呼び出すことにより、いずれかのxyインスタンス変数を設定することができます"*は、WaterDrop(DrawingPanelパネル、ブーリアン移動)で位置を決して与えないときです。 –

+0

これも私は混乱しています。私は学校に通っており、教授は「この開始位置はWaterDropオブジェクトを作成するオブジェクトによって設定されるべきです。つまり、xとyの位置を設定できる新しいコンストラクタが必要です」。 – user8865807

+0

コンストラクタの位置を証明していないので、コンストラクタパラメータを変更しないと位置を設定できません。このように、デフォルト値になるはずですが、その場所のパラメータを追加する必要があります。 [コンストラクタでコンストラクタを呼び出すことができます](https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java)には正当な理由がある。 –

答えて

0

「それは第二のコンストラクタを使用して、ドットを描画するとき、それは自動的に(0にそれらを設定し、 0)position "というのは、コンストラクタが初期化されるたびに新しいオブジェクトが作成されるからです。

+0

これは簡単に修正できますか? – user8865807

+0

次のコンストラクタ自体にxおよびyパラメータを指定します。 –

+0

新しいコンストラクタにパラメータを追加したので、2番目のコンストラクタは無意味ではないでしょうか? – user8865807

1

あなたの2番目のコンストラクタは、xyの適切な値を魔法のように "知る"ことはできません。あなたはにそれを与える必要があります適切な値。それを行う唯一の方法は、int xint y引数を追加することです。

public WaterDrop(int x, int y, DrawingPanel panel, boolean move) 
{ 
    this(x, y); // invoke the WaterDrop(int, int) ctor 
    this.panel = panel; 
} 

か、単に直接xyを設定します:

public WaterDrop(int x, int y, DrawingPanel panel, boolean move) 
{ 
    this.x; 
    this.y; 
    this.panel = panel; 
}