I am fairly new to Java (C++ and C are my usual languages)
I am trying to figure out how to sort an array of objects. I need to have users enter in how many players there are, Players names, and players scores. The program will then output the Scores and players names from Top to Bottom.
I have the users entering in the their info, and am storing it to a Player Class.
I cannot figure out how to sort the Players objects scores. I'm pretty sure I need to use a comparable, but for the life of me I cant figure out how to set it up.
Can anyone help?
I know the code in the player class isn't correct lol
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;
}
}