本文介绍了索引超出数组界限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,我不断收到消息索引超出数组的范围".另外,我无法获得lblAverage来显示平均值.我刚得到NaN.

代码:

Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCount.Click
        ''Determine word count and average letters / word in the sentence
        Dim iLength As Integer          ''length of string
        Dim iWords As Integer           ''number of words in sentence
        Dim iLetterCount As Integer     ''count of letters
        Dim sWord As String             ''current word
        Dim sPrevLetter As String       ''previous letter
        Dim x As Integer                ''loop counter
        Dim sLetter As String           ''current letter from sentence
        Dim sLine As String = txtInput.Text.Trim.ToLower    ''entered text  - no leading or trailing spaces - make all lowercase
        sLine = sLine.ToCharArray()
        Try
            iLength = sLine.Length + 1
            If iLength = 0 Then
                ''nothing entered
                MessageBox.Show("Please enter a sentence.")
            Else

            End If
            sWord = ""
            sPrevLetter = ""
            For x = 0 To iLength - 1
                sLetter = sLine.Chars(x)  ''get Next Letter
                Select Case sLetter
                    Case "a" To "z"
                        ''we are in a word - increment letter counter
                        sWord &= sLetter
                    Case Else
                        ''we are in a break between words
                        If sPrevLetter <> " " Then  ''we don''t want to count succesive spaces as a word
                            ''add word to list
                            lstLetters.Items.Add(sWord)
                            iLength = iLength + 1
                            sWord = "" '' reset for next Word
                        End If
                End Select
                sPrevLetter = sLetter
                If sLetter = "" Then
                    iLength += 1
                End If
            Next
            If sWord <> "" Then
                lstLetters.Items.Add(sWord)
                iLength = iLength + 1
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        lblWordCount.Text = "Words Counted: " & lstLetters.Items.Count
        lblAverage.Text = "Average letters per Word: " & iLetterCount / iWords

    End Sub
解决方案




这篇关于索引超出数组界限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:49