我在尝试将玩家的名字和得分加载到数组的第一个空地时遇到错误,但是它在数组中一遍又一遍地创建该名字的重复项。预先感谢
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
答案 0 :(得分:1)
您当前的代码将在找到的每个空索引中设置提供的值。找到空索引并设置其值后,您需要停止设置值(退出循环)。
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
如果第一个索引符合您的要求,则上面的代码将仅在循环中运行一次;如果第一个索引不符合您的要求,则重复两次;依此类推。
答案 1 :(得分:1)
为避免遍历数组寻找空插槽,请使用David Wilson在评论中建议的List(Of T)。 T代表Type,Player是Type。这会将您的列表限制为仅播放器类型的对象。我使用LINQ to Objects对您的列表进行了一些排序。有在线注释。尽管我认为列表是一种更好的方法,但是The White Wolf的Exit For答案应该可以解决您的问题。
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 IEnumberable(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