[Solved-2 Solutions] “Cannot find symbol” compilation error
Error Description:
- How to fix the error “Cannot find symbol” compilation error”?
Solution 1:
- Suppose that the compiler says "Cannot find symbol" for j.
- There are many ways you could "fix" that:
- You could change the inner
for
tofor (int j = 1; j < 10; j++)
- probably correct. - You could add a declaration for
j
before the innerfor
loop, or the outerfor
loop - possibly correct. - You could change
j
toi
in the innerfor
loop - probably wrong! and so on.
- The point is that you need to understand what your code is trying to do in order to find the right fix.
Solution 2:
Consider this code:
- Because neither of the variables named
message
is visible outside of their respective scope - which would be the surrounding brackets{}
in this case. - You might say: "But a variable named message is defined either way - so message is defined after the
if".
- Java has no
free()
ordelete
operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).
- "Oh, there's duplicated code, let's pull that common line out" -> and there it is.
- The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if: