我试图在Java中创建一个投票系统,在这个系统中,我输入一个候选人的名字和他们获得的选票数,然后我希望能够输出最高的选票和那个候选人的名字。到目前为止,我的主要方法是收集选票的名字和数目。它将这些信息放入两个数组中。一个字符串数组表示名称,一个int数组表示投票数。我可以使用一个返回int数组中最大数字的值方法来计算最高票数。然后,我没有任何问题地打印返回的值,但是我也希望能够从字符串数组中打印出获胜者的名字,因此我想知道是否有任何方法可以将字符串数组中的信息引用到int数组。为了完成程序,我需要使用两个单独的数组。到目前为止,这就是我所拥有的
import java.util.Scanner;
public class VotingCounter1
{
public static void main(String [] args){
Scanner userInput = new Scanner(System.in);
final int SIZE = 6;
int[] votes = new int[SIZE];
String[] names = new String[SIZE];
for (int i = 0; i < names.length && i < votes.length; i++){
System.out.print("Enter candidate's name: ");
names[i] = userInput.next( );
System.out.print("Enter number of votes: ");
votes[i] = userInput.nextInt( );
}
System.out.println("And the Winner is: " + highest(votes));
}
public static int highest(int[] votes){
int high = votes[0];
for (int i = 1; i < votes.length; i++){
if (votes[i] > high){
high = votes[i];
}
}
return high;
}
}发布于 2014-12-03 14:46:52
选票和候选人的索引是相同的,因为添加到相同的循环中。选票指数最高的是得票率最高的候选人。
System.out.println("And the Winner is: " + highest(votes,names));
public static String highest(int[] votes,String names[]){
int high = votes[0];
String s= names[0];
for (int i = 1; i < votes.length; i++){
if (votes[i] > high){
high = votes[i];
s=names[I];
}
}
s=s+""+high;
return s;
} 发布于 2014-12-03 14:08:29
最高票数的索引与候选人姓名的索引相同,因为您使用i在同一个循环中添加了它们。因此,得到最高票数的索引,你就可以得到相应候选人的名字。
发布于 2014-12-03 14:11:36
下面将给出得票最高的人的姓名。
names[Arrays.asList(names).indexOf(highest(votes))];请记住,这将找到最高(选票)的第一个例子。即。如果两人都有50票,那也是最高票数。得票后的名字就会被找到。
或者,使用具有名称和选票属性的对象。更好的设计
https://stackoverflow.com/questions/27273680
复制相似问题