2013-04-28 82 views
0

我想寫一個將信息打印到數組中的方法。方向如下:爲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語句。有什麼方法可以重新格式化這個工作嗎?

+0

你是對的,移動聲明以外的try – Kevin 2013-04-28 00:16:26

+0

我試過了,但問題是那段代碼依賴於上面的代碼(fileReader fr ...),它也可能會引發異常。 – cmart 2013-04-28 00:25:01

回答

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; 
} 

你需要拉外面的變量的聲明,但留下上試一試的內部分配給該變量。