为什么我的阵列排序? (Visual Basic)

时间:2015-08-07 17:23:14

标签: arrays vb.net sorting

我正在研究一个项目,对于学校来说,它将.txt文件中的文本读取到数组中。在这之后,我应该按字母顺序对数组进行排序,然后在列表框中列出内容。这是我的代码:

Imports System.IO
Public Class Form1
'Allow array to be accessed by the entire program

Public books(1) As String
Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
    'Declare variables

    Dim sr As New StreamReader("C:\Users\Bryson\Desktop\BooksinStock.txt")
    Dim book As String
    Dim i As Integer = 0
    'Establish loop to read contents of the text file into the array and list the array in the listbox
    'the sr.Peek = -1 simply means that the reader has reached the end of the file and there is nothing more to be read

    Do Until sr.Peek = -1
        book = sr.ReadLine()
        'ReDim allows the array to grow with the set amount of books in text file

        ReDim books(books.Length + 1)
        books(i) = book
        i += 1
    Loop
    Array.Sort(books)
    lstBoxInventory.Items.Add(books(i))


End Sub
End Class

然而,当我运行该程序时,我收到一个错误的lstBoxInventory.Items.Add(books(i))行,表示"类型' System.ArgumentNullException&#39的未处理异常;发生在System.Windows.Forms.Dll

我已尝试以各种方式列出代码以使其能够正常运行但仍然不断变通。有谁知道如何摆脱这个空错误?

1 个答案:

答案 0 :(得分:0)

发生问题因为“i”大于最高指数

if(condition){
  $('#education').rules("add",{min:3});
}
else {
  $('#education').rules("add",{min:4});
}

修改

老实说,我会改变格式以使用ReadAllLines和list(of String)

像(从内存中编写代码)

    Do Until sr.Peek = -1
    book = sr.ReadLine()

    ReDim books(books.Length + 1)
    books(i) = book
    i += 1 'This is adding 1 to the very end 
Loop
Array.Sort(books)
lstBoxInventory.Items.Add(books(i)) 'When the items are being added it is trying to add an extra i that does not exist

再次编辑

只是使用这个

Dim bookList as new List(of String)
Dim bookTextFile as String() = File.ReadAllLines("C:\booklist.txt")

for each book as String in bookTextFile
   bookList.add(book) 
next

bookList.Sort

创建单维数组..

Strings()是单个数组String(,)是二维数组

老实说,你的整个作业可能是

Dim bookList As String() = System.IO.File.ReadAllLines("C:\Users\Bryson\Desktop\BooksinStock.txt")
繁荣 - 完成。

使用

进行测试
Dim bookList As String() = System.IO.File.ReadAllLines("C:\Users\Bryson\Desktop\BooksinStock.txt")
Array.Sort(BookList)

你可以做到

for each book as String in BookList
     Msgbox(book)
next

但你真的会说bookList = books

但....如果您只是想让代码正常工作,那就试试吧

        Dim bookList As String() = System.IO.File.ReadAllLines("C:\Users\Bryson\Desktop\BooksinStock.txt")
    Dim books(bookList.Length - 1) As String 'This is the same as ReDim

    For x As Integer = 0 To bookList.Length - 1
        books(x) = bookList(x) 
    Next
    Array.Sort(books)