Java编译器错误:“找不到符号"尝试访问局部变量时 [英] Java compiler error: "cannot find symbol" when trying to access local variable

查看:186
本文介绍了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局部变量声明的范围:

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

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块

block 是括号内的一系列语句,局部类声明和局部变量声明语句.

A block is a sequence of statements, local class declarations and local variable declaration statements within braces.

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

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.

您可以通过将File checkFile;的声明作为getAllDirs方法的第一行来解决此问题;这将其范围作为该方法的其余部分.

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.

    • 比较棘手,因为变量是一个数组,具有特殊的初始化速记语法

    这篇关于Java编译器错误:“找不到符号"尝试访问局部变量时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆