Reputation: 13
public int getEntityIndex(String name){
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
break;
}
}
return i;
}
This code produces the error: i
cannot be resolved to a variable. I'm guessing that variables declared inside the for loop declaration are outside the scope of the remainder of the method, but I was unable to find any information regarding this problem specifically.
After analyzing the code for a while, I am starting to see that using it is a bad idea (what if entities[i]
never equals name
? The method will return entities.length - 1
, even if a match is not found. I think I'll use a while(!found)
approach instead.
To clarify, I'm not asking how to fix the issue. I'm asking why this error is occurring.
Thanks!
Upvotes: 0
Views: 326
Reputation: 401
public int getEntityIndex(String name){
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
return i; // If found return [i]
}
}
return -1; //[i] was not found and return = -1;
}
Upvotes: 0
Reputation: 31
You can use another variable to return de value.
public int getEntityIndex(String name){
int j = 0;
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
break;
}
j++;
}
return j;}
Upvotes: 0
Reputation: 72
The loop and everything is fine, but
return i;
.. i as a variable disappears once it leaves the loop, so the compiler doesn't actually know what to return. Here comes your error message
Upvotes: 0
Reputation: 2102
You cannot see i
outside the for
loop.
Try this:
public int getEntityIndex(String name) {
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
return i;
}
}
return -1;
}
PS: you could also use
entities[i].getName().equalsIgnoreCase(name)
instead of
entities[i].getName().toUpperCase().equals(name.toUpperCase())
Upvotes: 1
Reputation: 2599
i
is declared inside for
loop, it's scope is only inside the loop. You cannot return it because its outside of scope.
Upvotes: 0
Reputation: 746
In the last line, you return i
. The variable i
, however, was created inside the scope of a for loop and doesn't exist outside of the for loop where you are trying to return it.
You can return i
within the for loop, instead of "break." You would need to return something else at the end.
You could also initialize i
outside of the for loop.
Upvotes: 0
Reputation: 45736
i
is only in scope within the for
loop. You can't use it outside unless you explicitly extend the scope by either defining i
outside of the loop, or assigning it to another variable outside the loop.
Remember, a variable's scope is only within the block that it was defined. You're attempting to return i
, but i
doesn't exist outside the loop.
Upvotes: 0
Reputation: 53819
The scope of i
is the for loop: i
only exists in the for loop.
Therefore, i
cannot be used outside of it.
Upvotes: 0