2012-12-05 112 views
1

我製作的代碼旨在提供逐行讀取文本文件的功能,將每行保存到數組中。它似乎正確閱讀每行,但當我使用printProps()方法時,它只顯示一個...代碼僅將一行文本文件保存到數組中

代碼只保存一行文本文件到數組中,我的代碼有什麼問題?

/*reading in each line of text from text file and passing it to the processProperty() method.*/ 
Public void readProperties(String filename) { 
    try { 
     BufferedReader reader = new BufferedReader(new FileReader(filename)); 
     int i = 0; 
     String line; 
     line = reader.readLine(); 
     while (line != null && !line.equals("")) { 
      i++; 
      processProperty(line); 
      line = reader.readLine(); 
     } 
     System.out.println("" + i + " properties read"); 
    } catch (Exception e) { 
     System.err.println(e.getMessage()); 
     e.printStackTrace(); 

    } 
} 

/*Breaks up the line of text in order to save the value to an array (at this point it only saves one line to the array). org.newProp(newProp) passes the new property to the Organize class where it saves it to an array. 

public void processProperty(String line) { 
     org = new Organize(); 
     int id = nextPropertyID; 
     nextPropertyID++; 

     String[] parts = line.split(":"); 
     int propNo = Integer.parseInt(parts[0]);    
     String postcode = parts[1]; 
     String type = parts[2]; 
     int bedrooms = Integer.parseInt(parts[3]); 
     int year = Integer.parseInt(parts[4]); 
     int rental = Integer.parseInt(parts[5]); 
     Landlord landlord = theLandlord; 
     Tenant tenant = null; 
     org.propUniqueCheck(id); 
     propNoCheck(propNo, postcode); 
     postcodeCheck(postcode,propNo); 
     typeCheck(postcode, propNo, type); 
     bedroomsCheck(bedrooms, postcode, propNo); 
     yearCheck(propNo, postcode, year); 
     System.out.println("Creating property " + id); 

     Property newProp = new Property(id, propNo, postcode, type, bedrooms, year, 
       rental, landlord, tenant); 
     org.newProp(newProp); 
     org.printProps(); 
    } 

/*From here down it is the code to save the value to the array*/ 

public Organize() { 
     props = new ArrayList<Property>(); 
     PTs = new ArrayList<PotentialTenant>(); 
     waitingList = new LinkedList<String>(); 
     //myList.add(new prop(Property.toString())); 

    } 
    public void newProp(Property p) 
    { 
     props.add(p); 
    } 

我已經積極尋求在我的研討會,這個問題的幫助,我似乎無法找到解決的辦法,任何建議將非常感謝!

+1

哪裏printProps方法? –

+0

沒有printProps方法,我們不能幫你 – htz

回答

1

在processProperty中,您正在實例化一個新的Organize對象。因此,每個屬性(您爲每行創建的)都以不同的ArrayList結束(作爲第一個元素)。

一種解決方案是在啓動循環之前實例化一個對象Organize,然後將其作爲參數傳遞給processProperty方法。

+0

這是個問題,非常感謝你的幫助!這樣一個愚蠢的錯誤... –

+0

隨時接受答案;-) –

0

當文本文件中的一行是空字符串時,您的while循環會中斷。

這是實現循環的正確方法:

String line = ""; 
while ((line = reader.readLine()) != null) { 
    // your code here 
}