0

我有以下代码:

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,那么highscoreindex是2)。我想要代码做的是将当前的高分插入到正确的位置,并使其下方的高分和它替换的高分下降。它确实插入了当前的高分,但不会让其他人下降,我搞砸了什么?我应该怎么办?

4

1 回答 1

0

与其使用单独的数组,一个用于 name,一个用于 score,不如创建一个Class来保存两个关联的值。使该类实现IComparable以便他们可以自行排序。将您的类的实例保存在List()中,以便您可以针对它调用Sort() 。添加到列表并调用 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
于 2013-05-01T20:24:49.960 回答