$ 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);
}
}
Run Code Online (Sandbox Code Playgroud)
块中局部变量声明的范围是声明出现的块的其余部分,从其自己的初始化器开始,并包括局部变量声明语句中右侧的任何其他声明器.
阿块是声明,局部类声明和括号内的局部变量声明的语句序列.
你声明和初始化的方式checkFile,它们实际上是3个独立的局部变量,它们在各自块的末尾立即超出范围.
您可以通过将声明File checkFile;作为第一行getAllDirs方法来解决此问题; 这将其范围作为方法的其余部分.
| 归档时间: |
|
| 查看次数: |
2024 次 |
| 最近记录: |