首页 > 解决方案 > 索引数超过索引数组 vb 的维数

问题描述

在我调用我的函数的那一行的sub main中,我遇到了一个我不知道如何修复的错误:

索引数超过索引数组的维数

Module Module1
    Sub main()
        Dim names() As String = {"heimdall", "hella", "loki", "thor", "tyr", "odin"} 'list in order
        Dim last As Integer = names.Length - 1
        Dim first As Integer = 0
        Dim player As String = "thor"

        search(names(), last, first, player)

    End Sub

    Function search(ByVal names() As String, ByVal last As Integer, ByVal first As Integer, ByVal player As String)
        Dim midpoint As Integer = (first + last) \ 2
        Dim found As Boolean = False

        While found = False
            If last < first Then
                Return -1
            End If

            If names(midpoint) > player Then
                Return search(names, last, first, midpoint)
                found = True
            Else
                Return midpoint
                found = True
            End If
        End While


        Return midpoint 'automatically does this when found = true

    End Function

End Module

标签: vb.netrecursionbinary-search

解决方案


names()将其传递给search方法时删除末尾的括号。只有在声明数组时才需要这些。

search(names, last, first, player)

推荐阅读