gpt4 book ai didi

java - 如何对不同数据类型的数组进行排序

转载 作者:行者123 更新时间:2023-12-01 09:10:04 25 4
gpt4 key购买 nike

我正在尝试按字母顺序对候选人姓名进行排序,同时对候选人获得的选票进行排序,我使用了两个数组,一个用于姓名,另一个用于投票,因为我按选票排序,姓名数组需要在这里排序,我无法对其进行排序,请帮忙这是我的代码:

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();
}

}

最佳答案

创建一个Candidate类:

public class Candidate implements Comparable<Candidate> {
private String name;
private int votes;

public Candidate(String name, int votes) {
this.name = Objects.requireNotNull(name);
this.votes = votes;
}

// Getters and setters

@Override
public int compareTo(Candidate that) {
int c = this.name.compareTo(that.name);
if(c != 0) return c;
return this.votes - that.votes;
}
}

接下来创建这些候选人的列表并对它们进行排序:

List<Candidate> clist = new ArrayList<>();
// Add some Candidates to clist
Collections.sort(clist);

关于java - 如何对不同数据类型的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40973645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com