gpt4 book ai didi

java - 返回方法定义中的特定数组对象

转载 作者:行者123 更新时间:2023-11-30 02:47:39 25 4
gpt4 key购买 nike

我需要确定 PredatorList 数组中的哪个捕食者受到的伤害最大。由于某种原因,当我尝试返回该掠食者时,Eclipse 说 - mostDamaged 无法解析为变量。

为什么会这样?

public Predator mostDamagedPredator() {
// test if PredatorList contains predators
if (PredatorList.length > 0){
float difference = 0;
for (int i = 0; i < PredatorList.length; i++) {
if (PredatorList[i].getMaxHitPoints() - PredatorList[i].getHitPoints() > difference){
Predator mostDamaged = PredatorList[i];
}
}
return mostDamaged; // ERROR - mostDamaged cannot be resolved to a variable
}
// return null if there are no predators in PredatorList
return null;
}

最佳答案

您在 if 语句 block 内声明了 mostDamaged,因此它不在该 block 之外的范围内。

将其移到外面:

public Predator mostDamagedPredator() {
if (PredatorList.length > 0){
float difference = 0;
Predator mostDamaged = null;
for (int i = 0; i < PredatorList.length; i++) {
if (PredatorList[i].getMaxHitPoints() - PredatorList[i].getHitPoints() > difference){
mostDamaged = PredatorList[i];
}
}
return mostDamaged;
}
return null;
}

或者更好一点:

public Predator mostDamagedPredator() {
Predator mostDamaged = null;
if (PredatorList.length > 0){
float difference = 0;
for (int i = 0; i < PredatorList.length; i++) {
if (PredatorList[i].getMaxHitPoints() - PredatorList[i].getHitPoints() > difference){
mostDamaged = PredatorList[i];
}
}
}
return mostDamaged;
}

关于java - 返回方法定义中的特定数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com