Search code examples
javajava.util.scannerjavac

Getting "error: cannot find symbol"


I get the message

" Example.java:21: error: cannot find symbol

   Scanner finput = new Scanner(filed);
                                  ^

symbol: variable filed

location: class Example "

When I complile my program. I've tried looking this up but I can't figure out why I am getting this error.

Here is the code

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);
 }
}

Solution

  • As it has already been mentioned you need to move the declaration of the filed variable outside of the if statement. Your code can be something like this:

    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);
    }
    

    Now it works fine.