user14482437
user14482437

Reputation:

java gui show and sort ranking in sequence, descending order

I have a java GUI JFrame, it is working perfectly no error at the moment. I wish to add the ranking into my actionlistener. it is currently looking like this, no ranking number and not sorted in sequence (highest score to lowest score)

i wish to have the ranking shown, rank 1: A(77.83) rank 2: G(66.00) rank 3: C(33.99) etc... how can i show the ranking + sort them in order? highest score being rank 1, and lowest being rank 12.

enter image description here

this is the code i have

import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Olympic 
{
    private int NO=10;
    private String country;
    private double[] score = new double[NO];
    private int rank;
    
    public Olympic(String country)
    {
        this.country = country;
    }
    
    public Olympic (Olympic oly)
    {
        this(oly.country);
    }
    
    public void processScore()
    {
        for(int i=0; i <getScoreArray().length; i++)
            score[i] = Math.random()*100;
    }
    
    public double totalScores()
    {
        processScore();
        return Arrays.stream(score).sum();
    }
    
    public void set(int rank)
    {
        this.rank = rank;
    }   
    
    public int getRank()
    {
        return rank;
    }
    
    public String getName()
    {
        return country;
    }
    
    private double[] getScoreArray()
    {
        return score;
    }
    
    public String toString()
    {
        return String.format("Rank %d: %s (%.2f)",getRank(),getName(),totalScores());
    }
}

class OlympicFrame extends JFrame
{
    private JButton[] jbArray = new JButton[12];
    
    private final String[] countryArray = {"A", "B", "C", "D", "E", "F", 
    "G", "H", "I", "J", "K", "L"};
    
    private ArrayList<Olympic> alist = new ArrayList <Olympic> ();
    
    public OlympicFrame()
    {
        super ("RANKING 2020");
        setLayout (new GridLayout (4, 3));
        
        
        constructAList();

        //og code - how many countries in the array, how many button will be displayed
        jbArray = new JButton [countryArray.length];
        
        for (int i = 0; i<jbArray.length; i++)
        {
            jbArray[i] = new JButton(alist.get(i).getName());
            ImageIcon ic = new ImageIcon (alist.get(i).getName() +".jpg");
            
            jbArray[i].setIcon(ic);
            jbArray[i].setHorizontalTextPosition(SwingConstants.CENTER);
            jbArray[i].setVerticalTextPosition(SwingConstants.BOTTOM);
            
            
            jbArray[i].addActionListener((ActionEvent ae) ->
            {
                
            JOptionPane.showMessageDialog (null, getFinalRanking(), "ranking", JOptionPane.PLAIN_MESSAGE);
        
        });
        
        
        
        }
        
        for (int i = 0; i<jbArray.length; i++)
        {
            getContentPane().add(jbArray[i]);
        }

    }
    
    private void constructAList()
    {
        for (int i = 0; i<countryArray.length; i++)
        {
            alist.add(new Olympic(countryArray[i]));
        }
    }
    
        private int getRank(double[] scoreArray, double d)
    {
        int rank = 0;
        for (int i =0; i<scoreArray.length;i++)
        {
            if(d==scoreArray[i])
            {
                rank = i;
                alist.get(i).set(rank+1); //add into the list with rank+1, cause rank takes array and array starts from 0
            }
        }
                return rank;
    }
    

    private String getFinalRanking()
    {
        String ranking = "FINAL RANKING\n\n";
        for (int i = 0; i<alist.size(); i++)
        {
        ranking += alist.get(i).toString()+"\n";
        }
        return ranking;
    }
    
    private String getCountry(ArrayList<Olympic> alist, int n)
    {
        String country ="";
        for(int i =0; i<alist.size();i++)
        {
            if(alist.get(i).getRank() == n)
            {
                country = alist.get(i).getName();
            }
        }
        return country;
    }
    
    private double getScores(ArrayList<Olympic> alist, String name)
    {
        double total = 0;
        for(int i = 0; i<alist.size();i++)
        {
            if(alist.get(i).getName().equals(name))
            {
                alist.get(i).processScore();
                total=alist.get(i).totalScores();
            }
        }
        return total;
        
    }
    

}

class aaa
{
    public static void main (String [] args)
    {
        OlympicFrame of = new OlympicFrame();
        of.setSize (300, 500);
        of.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        of.setVisible (true);
    }
}

the main java looks like this before actionlistener

enter image description here

Upvotes: 0

Views: 818

Answers (1)

Rob Evans
Rob Evans

Reputation: 2874

I made some changes to getFinalRanking():

private String getFinalRanking() {
        Collections.sort(alist, (o1, o2) -> o1.scoreTotal() > o2.scoreTotal() ? 1 : o1.scoreTotal() == o2.scoreTotal() ? 0 : -1);

        int rank=1;
        for (Olympic olympic : alist) {
            olympic.setRank(rank++);
        }

        String ranking = "FINAL RANKING\n\n";
        for (int i = 0; i < alist.size(); i++) {
            ranking += alist.get(i).toString() + "\n";
        }
        return ranking;
    }

All the code (I've made some changes):

import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Olympic {

    private int NO = 10;
    private String country;
    private double[] score = new double[NO];
    private int rank;

    public Olympic(String country) {
        this.country = country;
        initScoresToRandomValues();
    }

    public Olympic(Olympic oly) {
        this(oly.country);
    }

    public void initScoresToRandomValues() {
        for (int i = 0; i < getScoreArray().length; i++)
            score[i] = Math.random() * 100;
    }

    public double scoreTotal() {
        return Arrays.stream(score).sum();
    }

    /**
     * easier to calculate this than it is to calculate + store the value when it could always be changing
     * @param rank
     */
    public void setRank(int rank) {
        this.rank = rank;
    }

    public int getRank() {
        return rank;
    }

    public String getName() {
        return country;
    }

    private double[] getScoreArray() {
        return score;
    }

    public String toString() {
        return String.format("Rank %d: %s (%.2f)", getRank(), getName(), scoreTotal());
    }
}

class OlympicFrame extends JFrame {

    private JButton[] jbArray = new JButton[12];

    private final String[] countryArray = {"A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L"};

    private ArrayList<Olympic> alist = new ArrayList<Olympic>();

    public OlympicFrame() {
        super("RANKING 2020");
        setLayout(new GridLayout(4, 3));

        constructAList();

        //og code - how many countries in the array, how many button will be displayed
        jbArray = new JButton[countryArray.length];

        for (int i = 0; i < jbArray.length; i++) {
            jbArray[i] = new JButton(alist.get(i).getName());
            ImageIcon ic = new ImageIcon(alist.get(i).getName() + ".jpg");

            jbArray[i].setIcon(ic);
            jbArray[i].setHorizontalTextPosition(SwingConstants.CENTER);
            jbArray[i].setVerticalTextPosition(SwingConstants.BOTTOM);

            jbArray[i].addActionListener((ActionEvent ae) ->
                JOptionPane.showMessageDialog(null, getFinalRanking(), "ranking", JOptionPane.PLAIN_MESSAGE));
        }

        for (int i = 0; i < jbArray.length; i++) {
            getContentPane().add(jbArray[i]);
        }
    }

    private void constructAList() {
        for (int i = 0; i < countryArray.length; i++) {
            alist.add(new Olympic(countryArray[i]));
        }
    }

    /**
     * builds up a string of the rankings
     * from an unsorted list
     * @return
     */
    private String getFinalRanking() {
        Collections.sort(alist, (o1, o2) -> o1.scoreTotal() > o2.scoreTotal() ? 1 : o1.scoreTotal() == o2.scoreTotal() ? 0 : -1);

        int rank=1;
        for (Olympic olympic : alist) {
            olympic.setRank(rank++);
        }

        String ranking = "FINAL RANKING\n\n";
        for (int i = 0; i < alist.size(); i++) {
            ranking += alist.get(i).toString() + "\n";
        }
        return ranking;
    }

    private String getCountry(ArrayList<Olympic> alist, int n) {
        String country = "";
        for (int i = 0; i < alist.size(); i++) {
            if (alist.get(i).getRank() == n) {
                country = alist.get(i).getName();
            }
        }
        return country;
    }

    private double getScores(ArrayList<Olympic> alist, String name) {
        double total = 0;
        for (int i = 0; i < alist.size(); i++) {
            if (alist.get(i).getName().equals(name)) {
                alist.get(i).initScoresToRandomValues();
                total = alist.get(i).scoreTotal();
            }
        }
        return total;
    }
}

class aaa {
    public static void main(String[] args) {
        OlympicFrame of = new OlympicFrame();
        of.setSize(300, 500);
        of.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        of.setVisible(true);
    }
}

I think this is what you want but do confirm if not.

If you don't like the sort order you can use:

Comparator<Olympic> olympicComparator = (o1, o2) -> o1.scoreTotal() > o2.scoreTotal() ? 1 : o1.scoreTotal() == o2.scoreTotal() ? 0 : -1;
Collections.sort(alist, olympicComparator.reversed());

Upvotes: 2

Related Questions