首页 > 解决方案 > 扫描仪对象的 Java“找不到符号”

问题描述

这是我的代码


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

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

标签: javajava.util.scanner

解决方案


该代码无法编译,因此您运行该程序是不可能的。

变量“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该类。

3)出现异常后应该退出程序,否则下面的代码会因为扫描仪没有初始化而失败。


推荐阅读