得到“错误:找不到符号”

时间:2017-05-15 03:26:49

标签: java java.util.scanner javac

我收到了消息

  

“Example.java:21:错误:找不到符号

   Scanner finput = new Scanner(filed);
                                  ^
     

符号:变量提交

     

location:class Example“

当我收集我的程序时。我已经尝试过了,但我无法弄清楚为什么会出现这个错误。

这是代码

public class Example
{

 public static void main(String[] args) throws Exception
 {
     java.io.File filer = new java.io.File("RESULT.txt");
     System.out.println("Choose the location of the data file");
     JFileChooser fileCh = new JFileChooser();
     if (fileCh.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        java.io.File filed = fileCh.getSelectedFile();
     }
     else {
         System.out.println ("No file choosen.");
         System.exit(1);

 }
     Scanner finput = new Scanner(filed);
 }
}

2 个答案:

答案 0 :(得分:0)

您收到此错误是因为正在从非法范围访问filed。尝试在if语句之外定义java.io.File filed。或许你想使用Scanner finput = new Scanner(filer)

答案 1 :(得分:0)

正如已经提到的那样,你需要在if语句之外移动filed变量的声明。你的代码可以是这样的:

public static void main(String[] args) throws Exception {
    java.io.File filer = new java.io.File("RESULT.txt");
    System.out.println("Choose the location of the data file");
    JFileChooser fileCh = new JFileChooser();
    java.io.File filed = null;

    if (fileCh.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        filed = fileCh.getSelectedFile();
    } else {
        System.out.println("No file choosen.");
        System.exit(1);

    }
    Scanner finput = new Scanner(filed);
}

现在工作正常。

相关问题