2017-04-09 72 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