所以我在编程方面仍然是一个新手,因此为什么我使用visual basic。我正在反复引发此异常,但是vb所说的变量具有未分配的值已在我的代码中给出了值。任何人都可以指出我在哪里出错吗?
编辑:只是更多细节:文件存在,我只能使用ReadLine方法读取它,但我需要拆分字段,以便我可以比较得分并得到最高的2分Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName() As String
Dim strScore() As String
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
答案 0 :(得分:0)
以下两个数组从未初始化:strName
和strScore
我不知道逻辑,但一种方法是使用List(Of String)
代替,它不需要首先获得正确的大小,并且可以调整大小。我还会使用Using
- 语句来正确处理流:
Using srdFile As New System.IO.StreamReader("HighScores.dat")
Dim strLine As String
Dim strField(1) As String
Dim strName As New List(Of String)
Dim strScore As New List(Of String)
Dim i = 0
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(","c)
strName.Add(strField(0))
strScore.Add(strField(1))
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i += 1
Loop
End Using
旁注:我建议默认情况下将Option Strict
设置为On
。
顺便说一句,这是一个完全不同的方法,但使用LINQ:
Dim lines = From line In IO.File.ReadLines("HighScores.dat")
Where Not String.IsNullOrWhiteSpace(line)
Let fields = line.Split(","c)
Let name = fields.First()
Let score = fields.Last()
Select String.Format("{0}, {1}", name, score)
rtbOut.Text = String.Join(Environment.NewLine, lines)
我发现这更具可读性。
答案 1 :(得分:0)
在使用阵列之前,需要在计算机内存位置分配固定的阵列大小。您可以通过使用数组元素的数量初始化数组来完成此操作。在您的代码中,在使用它们之前没有为strName()和strScore()分配任何内存,因此代码将抛出异常。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim strScore(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
您还可以创建动态数组。请关注Stackoverflow上关于动态数组的Resizing an array at runtime in VB.NET。