Reputation: 157
I need to determine which predator in my PredatorList
array has received the most damage. For some reason when I try to return that predator, eclipse says - mostDamaged
cannot be resolved to a variable.
Why is this so?
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;
}
Upvotes: 1
Views: 62
Reputation: 7496
This is because mostDamaged
is defined within the if
statement of your for
loop. This means where you want to return it the variable is not defined.
You can rewrite the method like this:
public Predator mostDamagedPredator() {
// test if PredatorList contains predators
Predator mostDamaged = null; // initialize it with 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]; // assign the correct item from the array
}
}
}
// either mostDamaged was initialized in the if statement or it is still null
return mostDamaged;
}
Upvotes: 0
Reputation: 5136
You have declared mostDamaged variable inside for context.
Declare it out, and initialize it there:
public Predator mostDamagedPredator() {
// test if PredatorList contains predators
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; // ERROR - mostDamaged cannot be resolved to a variable
}
// return null if there are no predators in PredatorList
return null;
}
Upvotes: 1
Reputation: 393781
You declared mostDamaged
inside an if
statement block, so it's not within scope outside that block.
Move it outside :
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;
}
or a little better :
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;
}
Upvotes: 1