我有以下代码:
Private Sub highscoreCheck()
Dim a As Integer, b As String, c As Integer
For a = 1 To 10
If highscore > lst_score(a) Then
highscoreIndex = a
Exit For
End If
Next
If highscoreIndex > 0 Then
For highscoreIndex As Integer = 1 To 10
b = lst_name(highscoreIndex)
c = lst_score(highscoreIndex)
If highscoreIndex = a Then
lst_name(highscoreIndex) = userName
lst_score(highscoreIndex) = highscore
Else
lst_name(highscoreIndex) = b
lst_score(highscoreIndex) = c
End If
Next
End If
End Sub
我有一个高分榜,由10行组成,而highscoreindex代表如果当前的高分大于任何和如果是,则highscoreIndex是最高的那些。 (如:12,8,6。当前的一个是9,那么高分数指数是2)。 我想要的代码是将当前的高分数插入到正确的位置并使其下面的那个和被替换的那个高分下来。 它确实插入了当前的高分,但没有让其他人失望,我搞砸了什么?我该怎么办?
答案 0 :(得分:0)
不要使用单独的数组,一个用于名称,一个用于得分,而是创建一个类来保存两个关联的值。使该类实现 IComparable ,以便他们可以自行排序。在列表()中保留课程实例,以便针对它调用排序()。添加到List并调用Sort()后,重复删除最后一个条目,直到左边只剩下所需的数字。
这是一个简单的例子:
Public Class Form1
Private Const MaxNumberOfHighScores As Integer = 3
Private HighScores As New List(Of ScoreEntry)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim score As New ScoreEntry
score.Name = "Bob"
score.Value = 7
AddEntry(score)
score = New ScoreEntry
score.Name = "George"
score.Value = 3
AddEntry(score)
score = New ScoreEntry
score.Name = "Dora"
score.Value = 9
AddEntry(score)
score = New ScoreEntry
score.Name = "John"
score.Value = 6
AddEntry(score)
score = New ScoreEntry
score.Name = "Jennifer"
score.Value = 10
AddEntry(score)
score = New ScoreEntry
score.Name = "Mike"
score.Value = 8
AddEntry(score)
For i As Integer = 0 To HighScores.Count - 1
Debug.Print(HighScores(i).Name & ": " & HighScores(i).Value)
Next
End Sub
Private Sub AddEntry(ByVal E As ScoreEntry)
HighScores.Add(E)
HighScores.Sort()
While HighScores.Count > MaxNumberOfHighScores
HighScores.RemoveAt(HighScores.Count - 1)
End While
End Sub
End Class
Public Class ScoreEntry
Implements IComparable(Of ScoreEntry)
Public Name As String
Public Value As Integer
Public Function CompareTo(other As ScoreEntry) As Integer Implements System.IComparable(Of ScoreEntry).CompareTo
Return other.Value.CompareTo(Me.Value) ' Sort Descending
End Function
End Class