dimanche 7 mars 2021

finding the largest attribute value in class and assigning the order

I have an ArrayList of a custom class named 'Team'.

Every object of 'Team' has an attribute of 'setsWon' with a value assigned.

Team also has an attribute of 'rank', that is set to null. I want to find the 'Team' with the largest number of 'setsWon', and assign 'rank' to 1, and then find the second largest 'setsWon' value, and assign its 'rank' to 2, and so on.

I have attempted, but i receive a null pointer exception, and its because I am only able to assign a rank to the largest 'setsWon' Team, and not any others.

this is my attempt:

// create temporary team list
        ArrayList<Team> temp = new ArrayList<>();
        // teams is my ArrayList of 'Team'
        for (Team t : teams.getTeamList()){
            temp.add(t);
        }
        for (int i = 0; i < teams.getTeamList().size(); i++){
            int max = 0;
            for (Team t : temp){
                if(t.getSetsWon() > max){
                    max = t.getSetsWon();
                }
            }
            if(temp.get(i).getSetsWon() == max){
                temp.get(i).setRank(i);
                temp.remove(i);

            }
        }

Team class:

public class Team {
    private String teamName;
    private ArrayList<Player> playerList = new ArrayList<>();
    private int matchesPlayed;
    private int matchesWon;
    private int setsWon;
    private int rank;

    public Team(String teamName){
        this.teamName = teamName;

// these values are set to 0 for another purpose I have in my project
        this.matchesPlayed = 0;
        this.matchesWon = 0;
        this.setsWon = 0;
    }

    public String getTeamName() {

        return teamName;
    }

    public void setTeamName(String teamName) {

        this.teamName = teamName;
    }

    public void setPlayerList(ArrayList<Player> playerList) {
        this.playerList = playerList;
    }

    public ArrayList<Player> getPlayerList() {
        return playerList;
    }

    public void add (Player player){
        playerList.add(player);
    }

    public void setMatchesPlayed(int matchesPlayed) {
        this.matchesPlayed = matchesPlayed;
    }

    public int getMatchesPlayed() {
        return matchesPlayed;
    }

    public void setMatchesWon(int matchesWon) {
        this.matchesWon = matchesWon;
    }

    public int getMatchesWon() {
        return matchesWon;
    }

    public void setSetsWon(int setsWon) {
        this.setsWon = setsWon;
    }

    public int getSetsWon() {
        return setsWon;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public int getRank() {
        return rank;
    }

    public String toString(){

        return String.format("%s", teamName);
    }

}

Aucun commentaire:

Enregistrer un commentaire