Reputation: 3
I have an error where I am trying to load a player's name and score to the first open space of the array, but it is creating duplicates of that name over and over in the array. Thanks in advance
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
Upvotes: 0
Views: 953
Reputation: 15091
To avoid looping through the array looking for an empty slot use a List(Of T) as suggested by David Wilson in comments. The T stands for Type and Player is a Type. This restricts your list to only objects of type Player. I included a bit to sort your list using LINQ to Objects. There are in line comments. Although I think a list would be a better approach, The White Wolf's answer with the Exit For should solve your problem.
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
Upvotes: 1
Reputation:
Your current code will set the supplied values in every empty index it finds. You need to stop setting the values (exit the loop) once you have found your empty index and set it's value.
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
The above code will only run through the loop once if the first index matches your requirements, twice if the first index does not but the second does and so forth.
Upvotes: 1