0

情報を配列に出力するメソッドを作成しようとしています。手順は次のとおりです。WordPath の 2 つ目のメソッドを作成します。makeWordArray は、文字列ファイル名を入力として受け取り、WordData オブジェクトを格納する配列または ArrayList を返します。

まず、メソッドは new FileReader(file) でファイルを開き、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 が見つからない問題を int で実行しています。それは try ステートメントにあるためだと思います。これを機能するように再フォーマットする方法はありますか?

4

1 に答える 1

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 の内側に残しておいてください。

于 2013-04-28T21:49:58.683 に答える