java - 扫描仪对象的 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
似乎扫描仪对象没有实例化,我不知道为什么。
解决方案
该代码无法编译,因此您运行该程序是不可能的。
变量“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)出现异常后应该退出程序,否则下面的代码会因为扫描仪没有初始化而失败。
推荐阅读
- reactjs - D3 图表不会在新数据上重绘
- amazon-web-services - Amazon Cognito 用户名重复
- javascript - 正则表达式搜索因特殊字符而失败
- react-native - 原生模块:{ Component } = NativeModules 和 requireNativeComponent('Component') 之间的区别
- prolog - Prolog 中的元解释逻辑剪切(编辑以容纳评论)
- php - 创建新博客文章时如何自动检查 Woocommerce 会员资格“禁用限制”复选框
- python - 与 plotly 一起使用的 locationmode 列表
- bash - BASH 仅在单个字母不在单词中时替换单个字母
- javascript - 如何从 element.all each 返回一个元素
- php - 与 MongoDB 的 PHP 连接不起作用并响应“试图获取无价值的属性”