Reputation: 1773
0 int specialFuncStart;
1 String[] specialFunctions= {"sum","ddx","integral"};
2 for(String element: specialFunctions){
3 specialFuncStart = finalMath.lastIndexOf("sum");
4 }
5 while (specialFuncStart != -1) { code }
Why does line 5
say that specialFuncStart
might not have been initialized? Strings are final and fixed, so the for loop will always run. Does the compiler not know that or am I missing something? I understand that initializing specialFuncStart = -1;
is how to fix it, but why?
Upvotes: 4
Views: 317
Reputation: 49
In the while loop you check for a condition with a variable which was initialized within a scope of another loop. Compiler will not let you do that considering the scenarios like it may not get initialized properly, that loop may not run or it may break early, even when its clear from our perspective that events will happen perfectly. The problem is with scopes, Java is a robust and strongly type language and its compiler checks every possibility to prevent misadventures.
Upvotes: 0
Reputation: 25
Compiler shows error because you initialize the specialFuncStart variable in the for loop and compileris not sure about whether it execute or not becuase in for-each loop array size can be 0 which makes it to not execute.
So you have initailise it before for loop like below to prevent error
specialFuncStart = 0;
Upvotes: 0
Reputation: 15320
You declared it but you didn't initialize it. You need to set a value to it:
int specialFuncStart; // declare
specialFuncStart = 0; // initialize
int specialFuncStart = 0; // both
Your compiler thinks that sometimes specialFuncStart
will not be initialized since a for
loop doesn't have to execute.
Upvotes: 2