Sorting numbers for highscores in java

青春壹個敷衍的年華 提交于 2020-01-03 03:05:51

问题


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;
}

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

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


回答1:


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...
}



回答2:


Create a class Player that contains both the name of the player and its score, and the appropriate getters (getName() and getScore()), and you'll be able to sort an array of Players with

 Player[] players = ...
 Arrays.sort(players, new Comparator<Player> {
     public int compare(Player p1, Player p2) {
         return Integer.valueOf(p1.getScore()).compareTo(p2.getScore());
     }    
 }


来源:https://stackoverflow.com/questions/9143328/sorting-numbers-for-highscores-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!