Java编译器错误:尝试访问本地变量时“找不到符号”

$ 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本地变量声明的范围 :

块中局部变量声明的范围是声明出现的块的其余部分,从其自己的初始化程序开始,并包括局部变量声明语句中右侧的任何其他声明符。

JLS 14.2块

是大括号内的语句,本地类声明和局部变量声明语句的序列。

你声明和初始化checkFile ,它们实际上是3个独立的局部变量 ,它们在各自块的末尾立即超出范围。

您可以通过放置File checkFile;的声明来解决这个File checkFile; 作为getAllDirs方法的第一行; 这将其范围作为方法的其余部分。

类似的问题

  • 变量无法解决
    • 变得棘手,因为变量是一个数组,它有一个特殊的初始化速记语法

变量存在于声明的块中,并在块完成后立即处理。

范围:在If / else语句之前声明checkFile