Java 尝试捕获异常块不工作
我的代码有点跳跃,但我想让它做的是:Java 尝试捕获异常块不工作,java,exception,arraylist,try-catch,Java,Exception,Arraylist,Try Catch,我的代码有点跳跃,但我想让它做的是: 当公共void在另一天运行时(在hive类中),for循环遍历arraylist并从中获取蜜蜂。然后它尝试对arraylist中的bee使用bee.anotherDay()方法 bee的另一个天()方法运行bee类的eat()方法-将蜜蜂的年龄加1,然后每3天(从第11天开始)向蜂巢中的arraylist添加一个鸡蛋 吃法-如果有足够的蜂蜜(2个或更多单位)将采取2蜂蜜,如果蜜蜂的健康是2或更少-将增加1。如果没有足够的蜂蜜,那么蜜蜂的生命值将减少1,如果生
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;
}
}
public void anotherDay(){//hive类中的anotherDay方法
对于(int i=0;i=2){
蜂巢;蜂蜜(2);
如果(健康==3){
}否则{
健康=健康++;
}
返回true;
}否则{
健康=健康-1;
如果(运行状况==0){
抛出新异常();
}
返回false;
}
}
第一条评论,这并不是异常的正确用法。您应该返回一个状态代码,可能是enum
第二条注释,从不抛出新异常()。创建您自己的异常
类,否则您将以完全相同的方式处理所有可能引发的异常(NullPointerException
,ArrayIndexOutOfBoundsException
等)。这是一个等待发生的错误
现在谈谈你的问题。您确实从列表中删除了索引i
处的项目,但始终在调用设置时将其重新添加
循环时切勿从集合中删除项目。事实上,除非必须,否则永远不要按索引循环集合
使用具有remove
方法的迭代器。这是在循环时从集合中删除的唯一(几乎唯一)安全方法
final Iterator<Bee> myIter = cells.iterator();
while(myIter.hasNext()) {
final Bee bee = myIter.next();
try{
bee.anotherDay();
}catch(Exception e){
myIter.remove();
}
}
也就是说,你的许多作业相当混乱。如果在if
中返回,则不需要else
。您的嵌套if
有点奇怪-有一个空语句肯定是代码味道
此外,如果不能从蜂巢
中提取蜂蜜,那么从蜂巢
中提取蜂蜜的逻辑实际上应该在的蜂巢中,可能会返回一个布尔值
。这就将您的方法简化为:
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;
}
public boolean eat()引发异常{
如果(蜂巢采蜜(2)){
如果(健康状况<3){
健康++;
}
返回true;
}
健康-=1;
如果(运行状况==0){
抛出新的BeeofHealthException();
}
返回false;
}
迭代器点请阅读:+1。删除一个项目,同时重复它的问题是一个错误等待发生!
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;
}