【发布时间】:2016-07-27 10:44:58
【问题描述】:
我遇到了这个问题:
btnDisplay_Click 过程应读取包含在 states.txt 文件中的五个名称,并将每个名称存储在一个五元素一维数组中。该过程应该对数组进行降序排序,然后在列表框中显示数组的内容。
使用我的代码,我可以在列表框中显示 5 个州的名称,但是它们没有被排序。
代码的第一次迭代(旧):
Public Class frmMain
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'Declare an array for 5 states
Dim strStates(4) As String
Dim strStateName As String
'Sort the array in descending order
Array.Sort(strStates)
Array.Reverse(strStates)
'Declare variable to hold stream reader object
Dim inFile As IO.StreamReader
'Check if txt file exists before opening to avoid run time error/crash
If IO.File.Exists("states.txt") Then
'Open the file
inFile = IO.File.OpenText("states.txt")
'Loop instructions until end of file is reached
Do Until inFile.Peek = -1
'Read a line
strStateName = inFile.ReadLine
'Add line (state) to list box
lstNames.Items.Add(strStateName)
Loop
'Close the file
inFile.Close()
Else
'Show a message box telling user file can't be found
MessageBox.Show("File does not exist or cannot be found.", "States", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
我也尝试将排序线放在循环内。如何让它在列表框中显示排序后的数组?
代码的第二次迭代(最新):
Public Class frmMain
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'Declare an array to hold all 5 states
Dim strStates(4) As String
'Declare variable to hold loop counts
Dim i As Integer = 0
'Declare variable to hold stream reader object
Dim inFile As IO.StreamReader
'Check if txt file exists before opening to avoid run time error/crash
If IO.File.Exists("states.txt") Then
'Open the file
inFile = IO.File.OpenText("states.txt")
'Loop instructions until end of file is reached
Do Until inFile.Peek = -1
'Read a line and store in array
strStates(i) = inFile.ReadLine
'Message box to confirm array loop is working correctly
MessageBox.Show(strStates(i))
'Manually increment array counter
i = i + 1
Loop
'Close the file
inFile.Close()
'Sort the array in descending order
Array.Sort(strStates)
Array.Reverse(strStates)
'Output to list box
lstNames.Items.Add(strStates(i)) 'error thrown here
Else
'Show a message box telling user file can't be found
MessageBox.Show("File does not exist or cannot be found.", "States", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
【问题讨论】:
-
您在将任何内容放入其中之前对数组进行排序。
-
是的,看起来问题实际上在于将文本文件中的单词放入数组中。我刚刚意识到代码没有这样做(因此,没有什么可排序的)。它只是将逐行读取的单词直接放入列表框中。我仍在努力,但感谢任何帮助。
-
帮自己一个忙,摆脱阵列。请改用
List(of string)。您将花费 5 分钟来学习如何使用它们。它们更好的方法之一是你不必知道它们有多大:它们自己调整大小。然后将strStateName添加到列表中。最后,使用列表作为数据源:lstNames.DataSource = myNameList。请务必在该方法之外声明列表。 -
感谢您的回复,很好的现实世界提示。不幸的是,这是课堂作业的额外功劳,因此必须以这种方式使用数组来完成。我现在已经成功地实现了数组,我只是在排序时遇到了问题。我编辑了我的 OP 以反映我的新代码。我认为排序问题涉及这样一个事实,即它是基于数组索引而不是字母进行排序的。仍在努力。
-
你在那个循环中做的太多了。在循环中将文件数据加载到数组中。接下来,对数组进行排序。最后,将数组元素添加到列表框。 (该数组没有真正的原因 - 您可以直接添加到 LB 并对其进行排序)。
标签: arrays vb.net visual-studio sorting text-files