[英]Why am I getting a “cannot find symbol” error when trying to use a local variable?
[英]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);
}
}
塊中局部變量聲明的范圍是該聲明在其中出現的其余部分,從其自己的初始化程序開始,並在局部變量聲明語句的右側包括其他任何聲明符。
塊是括號內的一系列語句,局部類聲明和局部變量聲明語句。
您聲明和初始化checkFile
的方式實際上是3個單獨的局部變量 ,它們在各自塊的末尾立即超出范圍。
您可以通過放置File checkFile;
的聲明來解決此File checkFile;
作為getAllDirs
方法的第一行; 這將其范圍作為該方法的其余部分。
作用域:在if / else語句之前聲明checkFile
變量位於聲明它的塊中,並在該塊完成后立即將其丟棄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.