$ 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);
}
}
$ javac GetAllDirs.java GetAllDirs.java:16: cannot find symbol symbol : variable checkFile location: class GetAllDirs
Share
JLS 14.4.2 Scope of Local Variable Declarations:
JLS 14.2 Blocks
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 ofgetAllDirsmethod; this puts its scope as the rest of the method.Similar questions