【问题标题】:Need help fixing a try, catch error需要帮助修复尝试,捕获错误
【发布时间】:2013-04-28 00:13:04
【问题描述】:

我正在尝试编写一种将信息打印到数组中的方法。方向是: 为 WordPath 创建第二种方法: makeWordArray 以字符串文件名作为输入,它返回一个数组或一个存储 WordData 对象的 ArrayList。

首先,该方法应使用 new FileReader(file) 打开文件,调用 numLines 方法获取文件中的行数,然后创建该大小的数组或 ArrayList。

接下来,关闭 FileReader 并重新打开文件。这次使用 BufferedReader br = new BufferedReader(new FileReader(file))。创建一个循环来运行调用 br.readLine() 的文件。对于从 br.readLine() 读取的每一行,调用该字符串上的 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 语句中。有没有办法重新格式化它以使其工作?

【问题讨论】:

  • 你是对的,把声明移到try外面
  • 我试过了,但问题是那段代码依赖于上面的代码(fileReader fr...),这也可能引发异常。

标签: try-catch drjava


【解决方案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 的内部。

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多