我的Array中有4个对象。 lastName,firstName,fighterKills,motherShipKills。我想要的是能够通过其中一个对象对其进行排序。 (按字母顺序或数字表示)。我将Array转换为String。我应该在转换之前或之后进行排序。
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class SpaceInvaders {
public SpaceInvaders() {
addData(lastName, firstName, fighterKills, motherShipKills);
sortBy();
print();
}
ArrayList<Player> players = new ArrayList<Player>();
String toString="";
Scanner scan = new Scanner(System.in);
int x = 10;
String lastName;
String firstName;
int fighterKills;
int motherShipKills;
public void addData (String lastName, String firstName, int figherKills, int motherShipKills) {
int x = 10;
System.out.println("Welcome to Space Invaders!");
for(int i = 0; i < x; i++) {
System.out.println("Please Enter Last Name or the name of your text file or if you are done entering please enter 'done': ");
lastName = scan.nextLine();
if(lastName.equals("done")) {
for (Player player : players) {
System.out.println(players);
break;
}
break;
}
else {
System.out.println("Please Enter First Name: ");
firstName = scan.nextLine();
System.out.println("Please Enter Fighter Kills: ");
fighterKills = scan.nextInt();
System.out.println("Please Enter Mothership Kills: ");
motherShipKills = scan.nextInt();
Player player = new Player(lastName, firstName, fighterKills, motherShipKills);
players.add(player);
String line;
System.out.println(players);
scan.nextLine();
}
}
}
public void sortBy () {
System.out.println("How would you like this sorted? 'Last Name'-1, 'First Name'-2, 'Fighter Kills'-3 or 'Mothership Kills'-4? ");
System.out.println("Please enter the number corresponding to the way you would like this sorted: ");
int sortBy = scan.nextInt();
if (sortBy == 1) {
System.out.println("Finished");
}
if (sortBy == 2 ){
System.out.println("Yee Buddy");
}
if (sortBy == 3) {
bestFighter();
}
if (sortBy == 4) {
bestMotherShip();
}
}
public String toString () {
for (Player play : players) {
toString += play.toString()+ "\n";
}
return toString;
}
public void print() {
}
public String bestFighter() {
}
public String bestMotherShip() {
String bestMotherShip = "Working";
System.out.println("Working");
return bestMotherShip;
}
public static void main(String[] args) {
SpaceInvaders tp = new SpaceInvaders();
System.out.println(" LAST NAME " + "\t" + " FIRST NAME " + "\t" + " FIGHTER KILLS " + "\t" + " MOTHERSHIP KILLS ");
System.out.println(" -------------------------------------------------------------------");
System.out.println( tp.toString());
}
}
所以我输入“Smith”,Bob“,”2“,24”然后“Joe”,“Shmo”,“3”,“15”。它会打印
Smith Bob 2 24
Shmo Joe 3 15
如果我希望它按照战斗机技能排序,它将改为
Shmo Joe 3 15
Smith Bob 2 24