2015-03-31 65 views
0

我被困在如何去閱讀/處理文件。文件的讀取和處理

示例文件:

2 

    cow 
    moo 
    black 
    and white very fast 

    pig 
    pink 
    very slow 

的2指示在該文件中的條目的數量。空行。然後是對象的名稱和兩行特徵。

基本上我很困惑,因爲最好的方法是逐行讀取輸入並處理它,以便我可以創建指定的對象。

我在想我可以創建一個數組列表,然後從那裏開始,但我不知道空白行分隔符將如何被採用。由於每個文件的元素數量可能不同,因此我不確定如何考慮這些因素。

+0

只需使用Scanner/BufferedReader,因爲您知道文件的結構。 – kolossus 2015-03-31 20:28:36

回答

0

這聽起來像你的問題是在概念層面比語法層次更多,所以我會嘗試在該層次上回答。

首先,我並不認爲開始的號碼是必需的,但您可以使用它來檢查您是否在事後跟蹤。

我認爲你應該創建一個描述你的對象的類,我們稱它爲「動物」類作爲參考。構造函數應該獲得一個數組列表,其中只包含與某個特定動物(您正在實例化的那個動物)相關的行的子集。該類的屬性應該是你需要的任何東西(例如名字等)。

所以在僞碼:

準備數組列表:

-read each line of file into arraylist 

消耗數組列表:

-read and save off the number of entries for checking later 
-read and ignore the first blank line 
-read line by line into another arraylist until the next blank line, pass your new array list to the constructor for your Animal class and then repeat this until you hit the end of file (making sure to construct the final object as well). 

「動物」 構造:

-Set the first entry in the arrayList passed to constructor as the animals Name. 
-Set remaining properties as required.... 

作爲你可以創造動物將它們存儲在一些數組中,最後您可以驗證您是否使用在開始時存儲的值創建了正確的數字。

相關問題