查找数组中的下一个空白空间



我有一个错误,我试图将玩家的名字和分数加载到数组的第一个开放空间,但它在数组中一遍又一遍地创建该名称的副本。提前致谢

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

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

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

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

为了避免遍历数组寻找空插槽,请使用 List(Of T(,正如 David Wilson 在注释中建议的那样。T 代表类型,播放器是类型。这会将列表限制为仅 Player 类型的对象。我包含了一些内容来使用 LINQ to Object 对列表进行排序。有行内评论。虽然我认为列表会是一个更好的方法,但白狼的答案与退出应该可以解决你的问题。

Structure Player
Public Score As Integer
Public Name As String
'Added a constructor to the structure to make it easy to add new Player
Public Sub New(myScore As Integer, myName As String)
Score = myScore
Name = myName
End Sub
End Structure
Private lstScores As New List(Of Player)
Private Sub BuildList()
lstScores.Add(New Player(500, "Mathew"))
lstScores.Add(New Player(200, "Mark"))
lstScores.Add(New Player(300, "Luke"))
lstScores.Add(New Player(700, "John"))
'Sort and display list
SortList()
End Sub
Private Sub AddScore(strName As String, intScore As Integer)
lstScores.Add(New Player(intScore, strName))
End Sub
Private Sub SortList()
'Note: the original lstScores is not changed
Dim orderedList = From scorer In lstScores Order By scorer.Score Descending Select $"{scorer.Score} - {scorer.Name}"
'orderedList is an IEnumerable(Of String) because the Select part of the LINQ query is a string.
'Using .ToList provides the DataSource of the ListBox with the formatted strings
'Display the sorted list in a list box
ListBox1.DataSource = orderedList.ToList
End Sub

最新更新