1

The code below produces the following error when I try to compile it:

cannot find symbol
symbol : variable airplanesFile

The error is produced by the last statement.

Why can the RandomAccessFile object not be found after it's declared?

Thanks!

public static void main(String[] args)
{

    try
    {
        RandomAccessFile airplanesFile = new RandomAccessFile("airplanesFile.ran", "rw");
    }
    catch (FileNotFoundException fnfe)
    {
        fnfe.printStackTrace();
    }

    airplanesFile.writeUTF("Test");
}
mg11
  • 11
  • 1

5 Answers5

2

This is to do with variable scoping. airplanesFile is declared within the braces of the try block. It goes out of scope when the compiler hits the closing brace of the try block.

Declare RandomAccessFile airplanesFile = null; before the try statement, and alter RandomAccessFile airplanesFile = new RandomAccessFile("airplanesFile.ran", "rw"); to airplanesFile = new RandomAccessFile("airplanesFile.ran", "rw"); and your problem should go away.

DaveH
  • 7,187
  • 5
  • 32
  • 53
  • Silly me... I forgot that try blocks are out of scope... Yasin also has a good point about placing the writeUTF method call in a try block since it can throw an IOException. I'm amazed at the speed, quantity, and quality of the responses. I'm definitely here to stay :-) Thanks!!! – mg11 May 03 '11 at 08:18
1

Because airplanesFile is only valid in try block. Try this:

public static void main(String[] args)
{
    RandomAccessFile airplanesFile = null;

    try
    {
         airplanesFile = new RandomAccessFile("airplanesFile.ran", "rw");
    }
    catch (FileNotFoundException fnfe)
    {
        fnfe.printStackTrace();
    }

    try {
        airplanesFile.writeUTF("Test");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Yasin Bahtiyar
  • 2,357
  • 3
  • 18
  • 18
0

It's out of scope. The try catch encloses the declaration.

If a variable/object is declared within a code block, inside any { } then it cannot be used outside of it. You have to do ...

airplanesFile.writeUTF("Test");

Inside the try catch, in your case.

Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
0

Because your airplanesFile is out of scope once the try block is done. See Scope of Local Variable Declarations

asgs
  • 3,928
  • 6
  • 39
  • 54
0

That's because airplanesFile is a local variable and exists only in the try block. Try reading about variable scopes in java.

Augusto
  • 28,839
  • 5
  • 58
  • 88