在java中为高分数排序数字 [英] Sorting numbers for highscores in java
问题描述
我的游戏有一个高分系统。我希望能够按照自动排序对数字进行排序,我有办法对数字进行排序
Ive got a highscore system for my game. and i want to be able to sort the numbers in acending order,ive got a way to sort the numbers
public static int[] sort(int[] a){
Arrays.sort(a);
return a;
}
但我怎么做才能让分数与玩家的名字保持一致那套呢?
例如
me:10
你:50
but how do i make it so the scores stay with the name of the player that set it? for example me:10 you:50
你应该是1号而我应该是nubmer 2.怎么样我使它在排序时使字符串与int保持一致?谢谢
You should be number 1 and me should be nubmer 2. how to i make it so that the string stays with the int when its sorted? thanks
推荐答案
最简单的方法是创建一个类来保存此人的姓名和分数。让它实现Comparable接口,在 compareTo(...)
方法中比较当前对象的分数, this
,传递给方法的对象,然后就像你正在做的那样对这个类的对象数组进行排序。
Easiest is to create a class to hold the person's name and score. Make it implement the Comparable interface, in the compareTo(...)
method compare the score of the current object, this
, to the object being passed into the method, and then sort an array of objects of this class just as you're doing.
class MyFoo implements Comparable<MyFoo> {
private String name;
private int score;
public MyFoo(String name, int score) {
// ... etc...
}
// getter methods here
public int compareTo(MyFoo other) {
return score - other.getScore();
}
//.... etc...
}
这篇关于在java中为高分数排序数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!