2017-04-09 25 views
0

正在做的一項小任務要求我通讀文本文件並將這些項目放入一個添加到ArrayList的對象中。但是,我發現難以使代碼正確工作。在文本文件中,項目是由空行分隔的5組。我的邏輯似乎沒有正確的工作,因此我尋求進一步的幫助。附件是文本文件,然後我的代碼正確讀取文本文件並將項目提供給類對象

Public Class BrowseReservations 
    Private objectStore As ArrayList = New ArrayList() 
    Private Shared basePath As String = My.Application.Info.DirectoryPath 
    Private Shared filePath As String = Path.Combine(basePath, "reservations.txt") 

    Private Sub populateList() 
     Dim counter As Integer = 0 
     objectStore.Clear() 
     Dim rc As ReservationRecord = New ReservationRecord() 
     Dim AllLines As String() = File.ReadAllLines(filePath) 
     For i As Integer = 0 To AllLines.Count() - 1 
      If counter = 0 Then 
       rc.setfullDate(AllLines(i)) 
      ElseIf counter = 1 Then 
       rc.setmonthName(AllLines(i)) 
      ElseIf counter = 2 Then 
       rc.sethoursChartered(Convert.ToInt32(AllLines(i))) 
      ElseIf counter = 3 Then 
       rc.setyatchName(AllLines(i)) 
      ElseIf counter = 4 Then 
       rc.setyatchLength(Convert.ToInt32(AllLines(i))) 
      ElseIf counter = 5 Then 
       rc.settotalCost(AllLines(i)) 
       objectStore.Add(rc) 
      ElseIf counter = 6 Then 'This is the empty space between groups 
       counter = -1 
      End If 
      counter += 1 
     Next 
    End Sub 
End Class 

這裏的文本文件,怎麼看起來像只是櫃面形象犯規出現的屏幕截圖。

2017年4月9日12時18分三十零秒
四月
卡塔利娜
$ 1235

2017年4月9日12點34分十九秒
四月
Hans Christin
$ 800

2017年4月9日十二時34分33秒
四月
霍比海
$ 7296

相反正確地進給各組,僅在最後一組在所述對象進料。有些內容也會丟失,例如Catalina(每個組的第4項中的字符串)。好心幫

+0

'昏暗c,如ReservationRecord =新ReservationRecord()' - 你需要ReservationRecord'的'多個實例來存儲所有的人,所以你知道。 –

+2

爲了擴展我所說的,保留一個'List(OfRetriebRecord)'並且每個組都有一個計數器,所以每次它到達空行時,添加計數器。然後在第一個(0)上創建一個新記錄並將其添加到您的列表中。然後不斷修改它直到6. –

+0

什麼可能導致某些信息(如字符串)丟失? –

回答

1

基於我和海姆·卡茨評論:

Public Class BrowseReservations 
Private objectStore As ArrayList = New ArrayList() 
Private Shared basePath As String = My.Application.Info.DirectoryPath 
Private Shared filePath As String = Path.Combine(basePath, "reservations.txt") 

Private Sub populateList() 
    Dim counter As Integer = 0 
    objectStore.Clear() 
    Dim rc As ReservationRecord 
    Dim AllLines As String() = File.ReadAllLines(filePath) 
    For i As Integer = 0 To AllLines.Count() - 1 
     If counter = 0 Then 
      rc = New ReservationRecord() 
      rc.setfullDate(AllLines(i)) 
     ElseIf counter = 1 Then 
      rc.setmonthName(AllLines(i)) 
     ElseIf counter = 2 Then 
      rc.sethoursChartered(Convert.ToInt32(AllLines(i))) 
     ElseIf counter = 3 Then 
      rc.setyatchName(AllLines(i)) 
     ElseIf counter = 4 Then 
      rc.setyatchLength(Convert.ToInt32(AllLines(i))) 
     ElseIf counter = 5 Then 
      rc.settotalCost(AllLines(i)) 
      objectStore.Add(rc) 
     ElseIf counter = 6 Then 'This is the empty space between groups 
      counter = -1 
     End If 
     counter += 1 
    Next 
End Sub 
End Class 
相關問題