public class Giocatore {
private String nome;
private int punteggio;
public Giocatore(String nome, int punteggio) {
this.nome = nome;
this.punteggio = punteggio;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getPunteggio() {
return punteggio;
}
public void setPunteggio(int punteggio) {
this.punteggio = punteggio;
}
@Override
public String toString() {
return "Giocatori [nome=" + nome + ", punteggio=" + punteggio + "]";
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class CreazioneSquadre {
private ArrayList<Giocatore> giocatori;
private String [] squadraA;
private String [] squadraB;
public CreazioneSquadre() {
giocatori = new ArrayList<Giocatore>();
squadraA = new String[5];
squadraB = new String[5];
}
public void creazioneGiocatori() {
Random random = new Random();
giocatori.add(new Giocatore("Giocatore1" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore2" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore3" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore4" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore5" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore6" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore7" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore8" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore9" , random.nextInt(10 - 1) + 1));
giocatori.add(new Giocatore("Giocatore10" , random.nextInt(10 - 1) + 1));
}
public void SortGiocatori() {
}
public void stampa() {
for (int i = 0; i < giocatori.size(); i++) {
System.out.println((i+1) + ") Nome: " + giocatori.get(i).getNome() + " Punteggio: " + giocatori.get(i).getPunteggio());
}
}
}
大家好,我正在尝试制作一个程序,让我成为一支足球队,这是我要改进的第一个版本。问题出在哪儿?我会对 ArrayList giocatori 进行排序,但它是一个类的 ArrayList,所以我在使用 Collections.sort() 时遇到了问题,我该怎么做排序呢?还有……你有什么建议可以让这个程序更好吗?这只是我在做的一个愚蠢的项目,因为每周我都会和我的朋友一起踢足球,我想为什么不创建一个让我们成为球队的计划。为了改进它,我喜欢将“puneggio”的值放在技能上,并用它来选择该玩家将要去的球队,现在如果随机选择它就足够了
答案 0 :(得分:1)
我相信这就是您要找的。您可以指定自己的比较器,而无需实际实现可比较的接口。
Giocatore
类的字段的比较器。public void SortGiocatori() {
Collections.sort(giocatori, Comparator.comparing(Giocatore::getPunteggio));
}