Error: cannot find symbol - Java compile error

1.1k Views Asked by At

I've been looking at this for a while now, and I'm sure the fix is right in front of me but I'm just blind to it. Someone care to point out why my int i is giving me an error?

CacheDownloader class:

  public static void main(String[] args) {
    String strFilePath = "./version.txt";
    try
    {
      FileInputStream fin = new FileInputStream(strFilePath);
     DataInputStream din = new DataInputStream(fin);
     int i = din.readInt();
       System.out.println("int : " + i);
       din.close();
    }
    catch(FileNotFoundException fe)
    {
      System.out.println("FileNotFoundException : " + fe);
    }
    catch(IOException ioe)
    {
      System.out.println("IOException : " + ioe);
    }
  }

    private final int VERSION = i; 

Error:

CacheDownloader.java:54: error: cannot find symbol
        private final int VERSION = i;
                                    ^
  symbol:   variable i
  location: class CacheDownloader
2

There are 2 best solutions below

2
On BEST ANSWER

i is declared in main, private final int VERSION is outside of main. Move it inside main or declare i as a global.

static int i=0;
public static void main(String[] args) {
    String strFilePath = "./version.txt";
    try
    {
      FileInputStream fin = new FileInputStream(strFilePath);
      DataInputStream din = new DataInputStream(fin);
      i = din.readInt();
      System.out.println("int : " + i);
      din.close();
    }
    catch(FileNotFoundException fe)
    {
       System.out.println("FileNotFoundException : " + fe);
    }
    catch(IOException ioe)
    {
       System.out.println("IOException : " + ioe);
    }
}
private final int VERSION = i;
2
On

You have to declare your int i before the try-catch block. Also, you have to declare your constant inside your main method:

  public static void main(String[] args) {
    String strFilePath = "./version.txt";
    int i;
    try
    {
      FileInputStream fin = new FileInputStream(strFilePath);
      DataInputStream din = new DataInputStream(fin);
      i = din.readInt();
      System.out.println("int : " + i);
      din.close();
    }
    catch(FileNotFoundException fe)
    {
      System.out.println("FileNotFoundException : " + fe);
    }
    catch(IOException ioe)
    {
      System.out.println("IOException : " + ioe);
    }
    final int VERSION = i; 
  }