からで、私はこれで問題を抱えている:Visual Basicのデータのソート読むとアレイは、テキストファイル
btnDisplay_Click手順は五にそれぞれ格納し、states.txtファイルに含まれている5人の名前をお読みください要素1次元配列。プロシージャは、降順で配列をソートし、リストボックスに配列の内容を表示する必要があります。
私のコードでは、5つの州名をリストボックスに表示することができますが、ソートされていません。 (旧)CODE OF
最初の反復:
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
私は同様に、ループ内のソート行を配置しようとしました。リストボックスにソートされた配列を表示するにはどうすればよいですか?
CODE OF 2回目の繰り返し(最新):
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
何かを入れる前に配列をソートしています。 – Plutonix
はい、問題は実際にテキストファイルから単語を配列に取り込むことにあります。私はちょうどコードがそれをしないことを理解しました(したがって、ソートするものはありません)。それは単にリストボックスに行の右に読み込まれた単語を置きます。私はまだそれに取り組んでいますが、どんな助けもありがとうございます。 –
自分で好きになり、配列を取り除く。代わりにリスト(文字列の)を使用してください。それらを使用する方法を学ぶために5分の時間がかかります。彼らがより良い方法の一つは、あなたがそれらを作るにはどれだけ大きなかを知る必要がないということです。次に、 'strStateName'をリストに追加します。最後に、リストをデータソースとして使用してください: 'lstNames.DataSource = myNameList'。そのメソッドの外にリストを宣言するようにしてください。 – Plutonix