Java 'cannot find symbol' 对于 Scanner 对象

Java 'cannot find symbol' for Scanner object

这是我的代码


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


每次我 运行 代码都会收到此错误:

java: 找不到符号 符号:变量扫描 位置:class LSArrayApp

似乎扫描仪对象没有实例化,我不明白为什么。

代码无法编译,所以你 运行 程序不可能是真的。

变量 "scan" 在 try 块之外是未知的。需要在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) 数组有固定的大小。要读取大小未知的文件,您可以使用 ArrayList class 代替。

3) 异常发生后请退出程序,否则下面的代码会因为扫描仪未初始化而失败。