tags:

views:

148

answers:

3
$ 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);
    }
}
+3  A: 

Scoping: Declare checkFile before your If/else statements

PartlyCloudy
Got fixed but now wondering why it works like that. Declaration, initialization, scoping --
HH
it seems that a declaration attaches a var to a block such such as if-else, method, class and perhaps something else.
HH
+3  A: 

A variable lives in the block it is declared in, and is disposed of as soon as that block completes.

meriton
+5  A: 

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


polygenelubricants
What is the def. of the term "block"?
HH
@HH: see edit for def of "block".
polygenelubricants
Can you call the error "Hole in Scope"? I assumed a scope but it was non-existent.
HH
The error is simply human error; you didn't fully understand the scoping rules of Java, which although nothing surprising, is still different (in a good way, most would say) than say Javascript. Please don't be offended: stackoverflow has seen its share of questions like this; it's definitely something that occasionally catches people once in a while.
polygenelubricants