Java compiler error: "cannot find symbol" when trying to access local variable
$ javac GetAllDirs.java
GetAllDirs.java:16: cannot find symbol
symbol : variable checkFile
location: class GetAllDirs
System.out.println(checkFile.getName());
^
1 error
$ cat GetAllDirs.java
import java.util.*;
import java.io.*;
public class GetAllDirs {
public void getAllDirs(File file) {
if(file.isDirectory()){
System.out.println(file.getName());
File checkFile = new File(file.getCanonicalPath());
}else if(file.isFile()){
System.out.println(file.getName());
File checkFile = new File(file.getParent());开发者_运维百科
}else{
// checkFile should get Initialized at least HERE!
File checkFile = file;
}
System.out.println(file.getName());
// WHY ERROR HERE: checkfile not found
System.out.println(checkFile.getName());
}
public static void main(String[] args) {
GetAllDirs dirs = new GetAllDirs();
File current = new File(".");
dirs.getAllDirs(current);
}
}
JLS 14.4.2 Scope of Local Variable Declarations:
The scope of a local variable declaration in a block is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
JLS 14.2 Blocks
A block is a sequence of statements, local class declarations and local variable declaration statements within braces.
The way you declared and initialized checkFile
, they're actually 3 separate local variables which goes immediately out of scope at the end of their respective blocks.
You can fix this by putting the declaration of File checkFile;
as the first line of getAllDirs
method; this puts its scope as the rest of the method.
Similar questions
- Variable cannot be resolved
- Made trickier because variable is an array, which has a special initialization shorthand syntax
A variable lives in the block it is declared in, and is disposed of as soon as that block completes.
Scoping: Declare checkFile before your If/else statements
精彩评论