gpt4 book ai didi

Java 多重构造函数设置问题

转载 作者:行者123 更新时间:2023-12-02 11:57:06 26 4
gpt4 key购买 nike

所以我在使用多个构造函数时遇到问题。基本上,我有两个 WaterDrop 构造,我将初始 x 和 y 位置(第二个代码块)传递到适当的构造函数中。问题是它没有将 int x, y 实例变量设置到适当的起始位置。它在第一个构造函数中将它们设置得很好,但是当它使用第二个构造函数绘制点时,它会自动将它们设置为 (0, 0) 位置。无论如何,我可以调用第一个构造函数,以便将 x 和 y 位置设置为适当的起始位置吗?

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


....
}

最佳答案

您的第二个构造函数不能神奇地“知道”xy 的适当值。您必须给它适当的值。唯一的方法是向其添加 int xint y 参数。然后,您可以通过调用第一个构造函数来设置 xy 实例变量:

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

关于Java 多重构造函数设置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47523635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com