我被难住了,需要另一双眼睛来看看这个。此代码正在工作,但突然停止工作。基本上我将一个对象添加到一个数组列表中。当我构建列表时,我会观察它,它似乎每次迭代都会添加一个唯一的对象。基本上是一个将出现在屏幕上的精灵及其 x、y 坐标、颜色和速度。早些时候,这很有效,精灵会分散在屏幕上,现在它似乎复制了添加到列表中的最后一个对象,我运行循环的 X 次最终得到相同的对象。这没有任何意义......
第一个 println 语句打印传递给构造函数的内容。所以它打印出来。
球:1 x:123 y:344 颜色:蓝色 球:2 x:3 y 233 颜色:绿色 球 3 x:24 y:3 颜色:蓝色
到目前为止,一切看起来都很棒。然后我实际上将列表打印到控制台,我得到了
球:1 x:24 y:3 颜色:蓝色 球:1 x:24 y:3 颜色:蓝色 球:1 x:24 y:3 颜色:蓝色
这就是我试图弄清楚为什么会发生这种情况的问题......
//When I create the List Eclipse refused to accept it until I initialized it like so...
java.util.List <Sprite> sprite = new java.util.ArrayList<Sprite>();
//yes I did import java.util.*; Eclipse still was digging it. This was working correctly despite the way i added it. I also changed this to a Vector which Eclispe was more content with with no effect.
private void GenerateSprites(){
//Random to keep it random
Random r = new Random(System.currentTimeMillis());
//variables for selecting and setting color
Color color = null;
int colorValue;
//variables for their x,y coordinates
float bX = 0;
float bY = 0;
//Create each ball set the color and generate the x,y coordinates
for (int x = 0; x < NUM_BALLS; x++){
colorValue = r.nextInt(4);
if (colorValue == 0) color = Color.BLUE;
if (colorValue == 1) color = Color.RED;
if (colorValue == 2) color = Color.YELLOW;
if (colorValue == 3) color = Color.GREEN;
bX = r.nextInt((int)(gameField.getWidth() - gameField.getWidth() / 4)+SCRN_MARGIN);
bY = r.nextInt((int)(gameField.getHeight() - gameField.getHeight() / 4)+SCRN_MARGIN);
//place the new ball in the gameField
//print the values being passed to the sprite constrcutor for debug purposes. The out put of this line indicates that all is well at this point.
System.out.println("Ball: " + x + " X: " + bX+ " Y: " + (bY+SCRN_MARGIN) + " Color: " + color.toString());
gSprite.add(new Sprite((float)bX, (float)bY+SCRN_MARGIN, BALL_SIZE, color));
}
//Now that the sprites are added to this list print out the list. When this line executes it shows a list of NUM_BALLS all of which have the exact sdame vlaues as the last sprite added earlier.
for (int x = 0; x < gSprite.size(); x++){
Sprite spr = gSprite.get(x);
System.out.println("Ball: " + x + " X: " + spr.getX()+ " Y: " + spr.getY() + " vX: " + spr.getvX() + " vY: " + spr.getvY() + " Color: " + spr.getColor().toString());
}
}