【发布时间】:2021-05-21 06:32:48
【问题描述】:
我正在创建一个程序,它创建将文件读取到数组中,将哪个文件分隔到数组中的不同索引值中。
static String[] readFile () {
int count = 0;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
// reads file into array
while (scanner.hasNextLine()) {
String[] data = new String[count];
int len = data.length;
for (int i = 0; i <= len; i++) {
data[i] = scanner.nextLine();
}
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
问题是,当尝试返回变量数据时,我收到一条错误消息“无法解析符号数据”,因为它是在 try-catch 块中初始化的。我尝试过 this 但它返回值 null 因为变量的长度由变量 count 确定,其值也在 catch 块中确定。提前致谢!
【问题讨论】:
-
您链接的帖子是这里的正确答案。您的问题不在于返回数组。您正在错误地读取文件。第一个循环已经读取了整个文件,所以第二个循环没有什么要读取的了。您需要关闭并重新打开文件,或使用
ArrayList,这样您就不需要计算行数。