扫描仪对象的Java'找不到符号'

时间:2020-02-19 21:17:06

标签: java java.util.scanner

这是我的代码


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:找不到符号 符号:变量扫描 位置:类LSArrayApp

看来扫描器对象没有实例化,我不知道为什么。

1 个答案:

答案 0 :(得分:2)

代码无法编译,因此您无法运行该程序。

在try块之外,变量“ scan”是未知的。您需要在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类。

3)发生异常后,您应该退出程序,否则以下代码将由于未初始化扫描仪而失败。

相关问题