0
我想按字母顺序排列候选人名称,同时对候选人获得的票进行排序,我把两个数组作为名称,另一个作为投票,因为我排序的名称数组需要在这里排序我可以“T使其排序,请帮助 这里是我的代码:如何对不同数据类型的数组进行排序
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();
}
}
我建议你创建一个保存姓名和投票数的一类。然后你可以创建一个这种类型的数组,当按票数进行排序时,你会得到正确的名字顺序。顺便说一句:数组中有[Sort](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-T:A-java.util.Comparator-) - 类 – Fildor
创建一个新的对象来封装名称和投票并存储在'ArrayList'中,并使用'Collections.sort'和自定义比较器 – GurV