0

我正在尝试将“M”切换为“先生”。和“F”到“女士”。在列表框中选择姓氏时。当我单击第一个名称时,它起作用了,但是当我单击任何其他名称时,我收到了以下错误消息:

--附加信息:索引超出了数组的范围。--

文本文件中的信息是这样的:

       Ball,Krystal,F,1981
       Banks,Robin,F,1988
       Burgher,Hamilton,M,1980
       Early,Brighton,M,1989
       Hedd,MT,M,1960
       Hogg,Ima,F,1953
       Knapp,Anita,F,1970
       Overnout,Roger,M,1968
       Psito,Arnie,M,1962
       Teak,Anne,F,1939

我的代码如下:

    Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
    Dim names As IO.StreamReader = IO.File.OpenText("Info.txt")
    Dim lName As String = lstNames.Text
    Dim line As String
    Dim gender As String
    Dim foundFlag As Boolean = False
    Do Until foundFlag Or names.EndOfStream
        line = names.ReadLine
        If line.Split(","c)(2) = "M" Then
            gender = "Mr. "
        ElseIf line.Split(","c)(2) = "F" Then
            gender = "Ms. "
        End If
        If line.Split(","c)(0) = lName Then
            txtOutput.Text = gender & line.Split(","c)(1) & " " & line.Split(","c)(0) & " is " & 2012 - line.Split(","c)(3)
            foundFlag = True
        End If
    Loop

End Sub

有人可以让我知道出了什么问题。提前致谢。

4

1 回答 1

0

我完全按照您在这里的方式重新创建了您的应用程序,并且运行良好。

这使我相信正在发生两件事之一:

  1. 您的Info.txt文件中有错误字符
  2. 您尚未lstNames使用与您在Info.txt.

PS - 您可能还想查看您的循环以使其更有效:

    Dim line() As String
    Dim gender As String
    Dim foundFlag As Boolean = False
    Do Until foundFlag Or names.EndOfStream
        line = names.ReadLine.Split(","c)

        If line(0) = lName Then
            If line(2) = "M" Then
                gender = "Mr. "
            ElseIf line(2) = "F" Then
                gender = "Ms. "
            End If
            txtOutput.Text = gender & line(1) & " " & line(0) & " is " & 2012 - cint(line(3))
            foundFlag = True
        End If
    Loop
于 2012-11-14T19:00:14.387 回答