-1

Its been a while since I did Java and so am going through a book. As far as I can see the following code is correct however I am having trouble compiling it. I used to use Scanner, but this book is taking this approach, and I would prefer to follow it and do the exercises as explained, can anyone see what is wrong here?

import java.io.*;

class ReadFile
{
public static void main( String[] args )
{

  try
  {
    FileReader file = new FileReader("Sheffield.data");
  }

  catch (IOException e)
  {
    System.out.println("A read error has ocurred" );
  }

  BufferedReader buffer = new BufferedReader(file);
  String line = "";

  while ((line = buffer.readLine()) != null)
  {
    System.out.println(line);
  }
  buffer.close();

}
}

The error I am getting in Windows cmd is as follows: enter image description here

Simple error I know, any help will be much appreciated.

FIXED!!

  BufferedReader buffer = new BufferedReader(file);
  String line = "";

  while ((line = buffer.readLine()) != null)
  {
    System.out.println(line);
  }
  buffer.close();

the above should all be placed in the try statement under the FileReader file = new FileReader("Sheffield.data");

Abbie
  • 153
  • 1
  • 3
  • 13
  • Variable scope. The name `file` is only usable within the `try` block. – Sotirios Delimanolis Jul 22 '15 at 18:27
  • This question has been updated and answered I guessed that was the issue. The book indicated to do the `BufferReader` statement outside the `try`, however the latter code block needed moving inside. Thanks for the help – Abbie Jul 22 '15 at 19:08

1 Answers1

0

file variable is created in the try block and thus BufferedReader buffer = new BufferedReader(file); doesnt have access to it. Create the reference before try and instantiate in th try block.

Shreyas Chavan
  • 1,079
  • 1
  • 7
  • 17
  • yeah that's exactly what I figured however its how this book says to do it, Mike McGrath - Java in Easy Steps 4th edition. – Abbie Jul 22 '15 at 18:54