-4

I have 4 variables that hold values as int x1, x2, x3 andx4. How do I sort them in descending order? (Code is shown below)

public void calculateButton() {

    totalVoterInteger = Integer.parseInt(totalVoters.getText());
    y1 = Integer.parseInt(projectOneVoters.getText());
    x1 = totalVoterInteger*y1;

    y2 = Integer.parseInt(projectTwoVoters.getText());
    x2 = totalVoterInteger*y2;

    y3 = Integer.parseInt(projectThreeVoters.getText());
    x3 = totalVoterInteger*y3;

    y4 = Integer.parseInt(projectFourVoters.getText());
    x4 = totalVoterInteger*y4;

    System.out.println(x1);
    System.out.println(x2);
    System.out.println(x3);
    System.out.println(x4);
  • 4
    Even if your implementation really only needs 4, it is way cleaner to store the values in a collection and then sort them – sshashank124 Feb 20 '18 at 13:10
  • Have you tried putting them in a list and using Collections.sort() method – Kleo G Feb 20 '18 at 13:11
  • Do you want the highest value or to know what fields hold the highest value ? The last one require a comparable POJO ! – AxelH Feb 20 '18 at 13:14
  • @sshashank124 I would say not a duplicate, but can be interesting to user7385522 to check this ! – NatNgs Feb 20 '18 at 13:22

1 Answers1

2

You can use sort function:

int[] arr = {x1, x2, x3, x4};
Arrays.sort(arr);
Salem
  • 13,516
  • 4
  • 51
  • 70
hsz
  • 148,279
  • 62
  • 259
  • 315