首页 > 解决方案 > 在数组中查找下一个空白空间

问题描述

我在尝试将玩家的姓名和得分加载到数组的第一个开放空间时出现错误,但它在数组中一遍又一遍地创建该名称的重复项。提前致谢

 Structure Player
    Dim Name As String
    Dim Score As Integer
End Structure

Public HighScores(100) As Player


 For i = 0 To 99
            If HighScores(i).Name = "" And HighScores(i).Score = 0 Then
                HighScores(i).Name = PlayerName
                HighScores(i).Score = CurrentScore
            Else
                i += 1
            End If
        Next

标签: arraysvb.net

解决方案


您当前的代码将在它找到的每个空索引中设置提供的值。找到空索引并设置它的值后,您需要停止设置值(退出循环)。

For i = 0 To 99

   If HighScores(i).Name.Length = 0 AndAlso HighScores(i).Score = 0 Then 'Determines if the index is empty

       HighScores(i).Name = PlayerName
       HighScores(i).Score = CurrentScore   'Sets the values

       Exit For    'Exits the loop

    End If

Next

如果第一个索引符合您的要求,上面的代码只会运行一次循环,如果第一个索引不匹配但第二个索引匹配,则运行两次,依此类推。


推荐阅读