我对 Java 还很陌生(C++ 和 C 是我常用的语言)
我正在尝试找出如何对对象数组进行排序。我需要让用户输入有多少玩家、玩家姓名和玩家得分。然后程序将从上到下输出分数和球员姓名。
我让用户输入他们的信息,并将其存储到玩家类中。
我不知道如何对玩家对象分数进行排序。我很确定我需要使用类似的工具,但我一生都不知道如何设置它。
有人可以帮忙吗?
我知道玩家类中的代码不正确哈哈
import java.util.*;
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
int allPlayers;
int index[] = new int[12];
int i= 0;
System.out.print("Please enter the number of players");
allPlayers = input.nextInt();
Player[] playersArray = new Player[allPlayers];
for(i = 0; i <allPlayers; i++){
playersArray[i] = new Player();
System.out.print("What is the name of Player # " + (i+1) +"?");
playersArray[i].name = input1.nextLine();
System.out.print("What was the score of Player # " + (i+1) + "?");
playersArray[i].score = input.nextInt();
}
System.out.print(playersArray[i].name);
System.out.print(playersArray[i].score);
}
}
public class Player implements Comparable<Player> {
private int score; // players score
private String name; // players name
public Player(int score, String name){
this.core = score;
this.name = name;
}
public int compareTo(Player other){
int last = this.score.compareTo(other.score);
return last == 0 ? this.name.compareTo(other.score) : score;
}
}
最佳答案
代码中的问题是对 compareTo()
方法的误解。
如果第一个参数(在本例中,this
被视为第一个参数)较大,则该方法返回 -1;如果相等,则返回 0;如果第二个参数更大,则返回 1。
public int compareTo(Player other){
if (other == null){
return -1; // If the other is null, it goes last
}
// First, compare by the score:
int scoreComparison = Integer.compare(this.score, other.score);
// That's good enough, unless the scores are equal
if (scoreComparison != 0){ // then they're not equal, so we know our answer
return scoreComparison;
} else { // The scores are equal, so compare the names and return the result
if (this.name == null){ // Equal if both null, otherwise non-null wins
return other.name == null ? 0 : 1;
} else {
return this.name.compareTo(other.name);
}
}
}
关于java - 尝试对 Java 对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862140/