I am trying to sort candidate names alphabetically while sorting votes gained by candidate,I took two arrays one for names and another for votes,as i sort by votes name array need to sort here i can't make it sort please help here is my code:
package com.sarga.Swinglearn;
import java.util.Scanner;
public class Project3 {
public static void main(String[] args)
{
int i=0,j=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter number of candidates");
int candcount = Integer.parseInt(s.nextLine());
System.out.println("Enter name of the candiadates");
String names[]=new String[candcount];//create an array
for( i=0;i<names.length;i++)
{
names[i]=s.nextLine();
}
System.out.println("candidates are: ");
for(i=0;i<candcount;i++)
System.out.println(names[i]);
for(i=0;i<candcount;i++)
{
for(j=i;j<candcount;j++)
{
if(names[i].compareTo(names[j])>0)
{
String temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
/*To sort names alphabetically*/
System.out.println("alphabetical order of candidates");
for(i=0;i<candcount;i++)
{
System.out.println(names[i]);
}
System.out.println("Enter number of votes of each candidate");
int votes[]=new int[candcount];
for(i=0;i<candcount;i++)
{
votes[i]=s.nextInt();
System.out.println(names[i]+":"+votes[i]);
}
//sort names based on their votes
System.out.println("List of candidates according to their votes");
//int max= votes[1];
int temp=0;
for(i=0;i<candcount-1;i++)
{
for(j=i;j<candcount;j++)
{
if(votes[i]<votes[j])
{
temp=votes[i];
votes[i]=votes[j];
votes[j]=temp;
}
}
}
for(i=0;i<candcount;i++)
System.out.println(names[i]+":"+votes[i]);
s.close();
}
}
ArrayListand useCollections.sortwith custom comparator