我收到以下错误:
printfile.java:6: error: cannot find symbol
throws FileNotFoundException {
^
symbol: class FileNotFoundException
location: class printfile
对于以下代码:
import java.io.File;
import java.util.Scanner;
public class printfile {
public static void main(String[]args)
throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println (" What file are you looking for? ");
String searchedfile = keyboard.next();
File file = new File(searchedfile);
if (file.exists()) {
System.out.println(" Okay, the file exists... ");
System.out.print(" Do you want to print the contents of " + file + "?");
String response = keyboard.next();
if (response.startsWith("y")) {
Scanner filescan = new Scanner(file);
while (filescan.hasNext()) {
System.out.print(filescan.next());
}
}
else {
System.out.print(" Okay, Have a good day.");
}
}
}
}
如何解决此错误?
最佳答案
要使用不在程序“范围”内的类(即 FileNotFoundException
),您必须:
调用它的完全限定名称:
// Note you have to do it for every reference.
public void methodA throws java.io.FileNotFoundException{...}
public void methodB throws java.io.FileNotFoundException{...}
或者
从包中导入类:
// After import you no longer have to fully qualify.
import java.io.FileNotFoundException;
...
public void methodA throws FileNotFoundException{...}
public void methodB throws FileNotFoundException{...}
建议也看看 this问题,几乎解释了您可能想了解的有关 Java 访问控制修饰符的所有内容。
关于java - 错误: cannot find symbol: class FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177395/