【发布时间】:2014-12-03 14:03:33
【问题描述】:
我正在尝试在 Java 中创建一个投票系统,在其中输入候选人的姓名和他们获得的票数,然后我希望能够输出最高票数以及该候选人的姓名。到目前为止,我所拥有的是一种收集姓名和票数的主要方法。它将这些信息放入两个数组中。一个字符串数组用于名称,一个 int 数组用于投票数。我可以使用返回 int 数组中最大数字的 value 方法来计算最高票数。然后我打印返回的值没有任何问题,但我也希望能够从字符串数组中打印出获胜者的姓名,所以我想知道有什么方法可以将字符串数组中的信息引用到 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;
}
}
【问题讨论】:
标签: java arrays methods counter voting