【发布时间】:2013-12-07 20:49:26
【问题描述】:
好的,所以我有一个蜂箱模型,其中包含一个称为单元格的蜜蜂数组列表。我想要发生的是当蜜蜂健康达到 0 时,它会从数组列表中删除(鸡蛋不需要吃)。蜜蜂的年龄每天增加 1,如果有足够的食物喂它,它的健康也会增加 1(最多 3)。如果没有足够的食物,那么生命值会减少 1(直到它从数组列表中删除时达到 0)。蜜蜂类是抽象的,并且有子类,如卵、幼虫、蛹等。当卵的年龄 > 3 岁时,它会变成幼虫,而幼虫会在 7 岁时变成蛹。但是,我在编码时遇到了严重的问题。如果健康达到0罚款,我已经设法获得喂养,健康增加/减少和移除,但我无法弄清楚如何将我的卵“进化”成幼虫。
我的代码:
public class Hive {
ArrayList<Bee> cells = new ArrayList<Bee>();
//some code omitted
public void anotherDay(){
for(int i = 0;i<cells.size(); i++){
System.out.println(cells.get(i));
Bee bee = cells.get(i);
try{
bee = bee.anotherDay();
}catch(Exception e){
cells.remove(i);
}
}
女王级:
public class Queen extends Bee{
//some code omitted
public Bee anotherDay() throws Exception{
eat();
age++;
if(age%3 == 2){
hive.addBee(new Egg());
}
return this;
}
public boolean eat() throws Exception{
if(hive.honey >= 2){
hive.takeHoney(2);
if(health < 3){
health++;
}return true;
}
health -= 1;
if(health == 0){
throw new Exception();
}
return false;
}
卵类(幼虫和蛹的方法类似):
public class Egg extends Bee {
//some code omitted
public Bee anotherDay(){
age = age++;
if (age>3){
return new Larvae();
}else{
return this;
}
}
【问题讨论】:
标签: java class exception arraylist