java - 尝试对 Java 对象数组进行排序

标签 java arrays sorting

我对 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/

相关文章:

java - Selenium : Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code

java - 我可以对代码执行哪些操作来跳过输入文本文件的第一行?

C++图像过滤算法

php - 排列数组变量

java - 如何使用 Collections.sort() 使我的数组按字母顺序排序? -Java

php - 我如何从 mysql 查询创建这个数组?

Java 流压缩两个列表

java - 了解具有多个类的多态性和实例化的接口(interface)形式

php - 获取MySQL在特定时间添加的信息

Java Collections.sort() 排除字符范围