2017-09-01 113 views
-1

我正在嘗試讀取標題爲「inventory.txt」的文本文件並將其保存到不同的數組。我得到indexOutOfRangeException是未處理的錯誤。當我通過我的代碼並將鼠標懸停在「itembulkAmt」上時,它顯示文本文件中不同行的信息,因爲某些項目沒有大量數量或價格,如任天堂開關。我很難堅持任何幫助,將不勝感激。這是文本文件看起來像:得到indexOutOfRangeException是未處理的錯誤

橡皮泥,3.95,10,2.99
傻串,3.50,10,2.77
任天堂開關,429.99
馬里奧賽車(開關),49.99
Code Jam Challenge(Switch),47.99
Fidget Spinner,6.79,5,5.98
Rubik's cube,9.10
'編程規則!'按鈕,0.79,20,.47
'編程規則!'保險槓貼紙,0.99,20,0.78
瓶Ø氣泡,0.99

'read and validate inventory text file 
    Dim invntFile As StreamReader 
    If File.Exists("inventory.txt") Then 
     invntFile = File.OpenText("inventory.txt") 
     Dim indexInvnt As Integer = 0 
     While Not invntFile.EndOfStream 
      Dim entirelineInvnt = invntFile.ReadLine 
      Dim inventory() As String = entirelineInvnt.Split(","c) 
      Dim itemName As String = inventory(0) 
      Dim itemPrice As Double = CDbl(inventory(1)) 
      Dim itemBulkAmt As Double = CDbl(inventory(2)) 
      Dim itemBulkPrice As Double = CDbl(inventory(3)) 
      itemLabel(indexInvnt) = itemName 
      priceReg(indexInvnt) = itemPrice 
      amtBulk(indexInvnt) = itemBulkAmt 
      priceBulk(indexInvnt) = itemBulkPrice 
      indexInvnt += 1 
     end while 
    end if 
+0

請閱讀[問]並參加[導覽](也有小工具欄上用於格式化帖子的工具和幫助) – Plutonix

+0

您可以使用Try Catch塊輕鬆處理此問題 –

+0

文件中的某些行不包含4個元素。您的代碼將在這些行中引發異常。 –

回答

2

並非所有的項目有三個價格。因此,庫存(2)和庫存(3)正在拋出索引錯誤。

相關問題