mg11
mg11

Reputation: 11

RandomAccessFile cannot be found by compiler after being declared

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

Upvotes: 1

Views: 668

Answers (5)

Yasin Bahtiyar
Yasin Bahtiyar

Reputation: 2367

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

Upvotes: 1

DaveH
DaveH

Reputation: 7335

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.

Upvotes: 2

Augusto
Augusto

Reputation: 30062

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

Upvotes: 0

asgs
asgs

Reputation: 3984

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

Upvotes: 0

Manuel Salvadores
Manuel Salvadores

Reputation: 16525

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.

Upvotes: 0

Related Questions