我有一个方法,我正在尝试使用自己的迭代器来访问我的游戏对象集合中的两个不同对象。我首先尝试访问foodstation(对象)并获得它的容量并将其存储到fStationCapacity中。然后我尝试访问我的Ladybug(对象)并通过fStationCapacity增加它的foodlevel,但我无法得到它,因为它永远不会达到if语句。我该如何尝试解决此问题?
public void init() {
theGameCollection = new GameObjectCollection();
theGameCollection.add(Ladybug.getLadyBug());
theGameCollection.add(new Flag(210.0,100.0));
theGameCollection.add(new Flag(800.5, 200.2));
theGameCollection.add(new Flag(364.5, 754.0));
theGameCollection.add(new Flag(568.5, 422.5));
theGameCollection.add(new Flag(540.0,280.0));
theGameCollection.add(new Flag(954.0, 155.2));
theGameCollection.add(new Flag(666.0, 689.0));
theGameCollection.add(new Flag(489, 900.5));
theGameCollection.add(new Flag(600.4, 777.5));
theGameCollection.add(new Spider());
theGameCollection.add(new Spider());
theGameCollection.add(new FoodStation());
theGameCollection.add(new FoodStation());
}
public void collisionWithFood() {
IIterator theObjects = theGameCollection.getIterator();
IIterator theObjects2 = theGameCollection.getIterator();
int fStationCapacity = 0;
int foodlevel= 0;
while (theObjects.hasNext()) {
GameObject go = (GameObject) theObjects.getNext();
while (theObjects2.hasNext()) {
GameObject go2 = (GameObject) theObjects2.getNext();
if ((go instanceof FoodStation && go2 instanceof Ladybug) && ((FoodStation)go).getCapacity() != 0 ) {
fStationCapacity = ((FoodStation)go).getCapacity(); //gets the food station capacity and stores into into fStationCapacity
((FoodStation)go).reduceCapacity(); //reduces the food station's capacity food level to zero
((FoodStation)go).setColor(144, 238, 144); //changes the color of the food station to light green
((Ladybug)go2).increaseFoodLevel(fStationCapacity);
System.out.println("LadyBug has collided with a foodStation of capacity: " + fStationCapacity);
System.out.println("Capacity" + fStationCapacity + "\nCurrent Food Level" + foodlevel);
break; //breaks because I only want one instance
}
}
}
theGameCollection.add(new FoodStation()); //creates a new food station with random location and random size
}
答案 0 :(得分:1)
可能theGameCollection.getIterator()总是返回相同的迭代器。相反,你应该为两个循环创建2个不同的迭代器