需要帮助修复尝试,捕获错误

时间:2013-04-28 00:13:04

标签: try-catch drjava

我正在尝试编写一个将信息打印到数组中的方法。方向是:为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;
}  
}

我正在运行一个无法找到变量newArray的问题,我相信因为它在try语句中。有没有办法重新格式化这个工作?

1 个答案:

答案 0 :(得分:1)

像这样:

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的内部。