0

This is my code


import java.util.*;
import java.io.*;

public class LSArrayApp{
    public static void main(String[] args){
        System.out.println(ReadFile());

    }


    public static String[] ReadFile(){

        try{
            File myFile =new File("fileName.txt");
            Scanner scan = new Scanner(myFile);
            System.out.println("Scanner creation succesful");
            }


        catch(FileNotFoundException e){
            System.out.println("File not found");
            }


        String[] data =  new String[2976];        
        int lineNumber = 0;
        while (scan.hasNextLine()){
            data[lineNumber] = scan.nextLine();
            lineNumber++;

        return data;
        }


Everytime I run the code I get this error:

java: cannot find symbol symbol: variable scan location: class LSArrayApp

It seems that the scanner object is not instantiating and I can't figure out why.

  • 1
    `scan` is defined with the context of the `try-catch` block, it is not accessible out side of it, in fact, you shouldn't trust it as you wouldn't know if it was successful initialised or not without doing a `null` check first. Ok, having said all that. Move the rest of the code instead the `try-catch` block, or better, remove the `try-catch` and simply allow the exception to be thrown from the method so that the caller becomes responsible for dealing with it – MadProgrammer Feb 19 '20 at 21:19

1 Answers1

2

The code does not compile, so it cannot be true that you run the program.

The variable "scan" is unknown outside the try block. You need to declare it before try.

Scanner scan;
try
{
    File myFile =new File("fileName.txt");
    scan = new Scanner(myFile);
    System.out.println("Scanner creation succesful");
}
catch(FileNotFoundException e)
{
    System.out.println("File not found");
    System.exit(1);
}

2) Arrays have a fixed size. To read a file with unknown size you may use the ArrayList class instead.

3) After the exception you should exit the program, otherwise the code below will fail because the scanner is not initialized.

Stefan
  • 1,789
  • 1
  • 11
  • 16