需要帮助修复一个尝试,赶上错误
问题描述:
我想写一个将信息打印到数组中的方法。方向如下:为WordPath创建第二个方法: makeWordArray以String文件名作为输入,并返回存储WordData对象的数组或ArrayList。需要帮助修复一个尝试,赶上错误
首先,该方法应该用新的FileReader(文件)打开文件,调用numLines方法获取文件中的行数,然后创建一个数组或具有该大小的ArrayList。
接下来,关闭FileReader并重新打开文件。这次使用BufferedReader br = new BufferedReader(new FileReader(file))。创建一个循环来运行调用br.readLine()的文件。对于从br.readLine()中读取的每一行,请调用该String上的parseWordData以获取WordData,并将WordData对象存储到数组或ArrayList的相应索引中。
我的代码是:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
我正在INT其中变量newArray不能发现一个问题,我相信,因为它是在try语句。有什么方法可以重新格式化这个工作吗?
答
像这样:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
你需要拉外面的变量的声明,但留下上试一试的内部分配给该变量。
你是对的,移动声明以外的try – Kevin 2013-04-28 00:16:26
我试过了,但问题是那段代码依赖于上面的代码(fileReader fr ...),它也可能会引发异常。 – cmart 2013-04-28 00:25:01