我的代码跳过了一点,但我想要它做的是:
通过使用println几次,我认为实际发生的情况是,我的异常被抛出并捕获,但蜜蜂并没有被从数组中移除。
我的代码:
public void anotherDay(){ //anotherDay method in hive class
for(int i = 0;i<cells.size(); i++){
Bee bee = cells.get(i);
try{
bee = bee.anotherDay();
}catch(Exception e){
cells.remove(i);
}
cells.set(i, bee);
}
}
public Bee anotherDay() throws Exception{ //anotherDay mehtod in my Queen class (subclass of Bee}
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){
}else{
health= health++;
}
return true;
}else{
health = health -1;
if(health == 0){
throw new Exception();
}
return false;
}
}发布于 2013-12-07 12:36:33
首先,这并不是对Exception的正确使用。您应该返回一个状态代码,可能是一个enum。
第二条评论,从不 throw new Exception()。创建您自己的Exception类,否则您将完全按照samne方式处理可能抛出的所有异常(NullPointerException、ArrayIndexOutOfBoundsException等)。这是一个等待发生的错误。
现在谈谈你的问题。您确实将索引i中的项从List中删除,但是总是通过调用set将其添加回set。
不要在循环时从Collection中删除项。事实上,除非您必须这样做,否则永远不要按索引遍历集合。
使用具有Iterator方法的remove。这是在循环时从集合中删除的唯一(几乎唯一的)安全方法。
final Iterator<Bee> myIter = cells.iterator();
while(myIter.hasNext()) {
final Bee bee = myIter.next();
try{
bee.anotherDay();
}catch(Exception e){
myIter.remove();
}
}不需要再用一天的方法返回this,也不需要用完全相同的引用替换List中的引用。
看看您的eat方法,可能会有相当多的整理工作;我建议如下:
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 BeeOutOfHealthException();
}
return false;
}也就是说,你的许多作业都很混乱。如果在else中使用return,则不需要if。嵌套的if有点奇怪--有一个空语句当然是代码的味道。
此外,从hive中提取蜂蜜的逻辑应该在蜂巢中,因为如果不能获取那么多蜂蜜,takeHoney可能会返回一个boolean。然后将您的方法简化为:
public boolean eat() throws Exception{
if(hive.takeHoney(2)){
if(health < 3){
health++;
}
return true;
}
health -= 1;
if(health == 0){
throw new BeeOutOfHealthException();
}
return false;
}https://stackoverflow.com/questions/20441347
复制相似问题