我是一个尝试学习Java的初学者,事实证明数组很困难。请多多包涵,我不知道所有正确的术语,而且我也不擅长解释事物。
我正在尝试编写一个程序来计算每个候选人的选票。这些选票由用户输入。示例:候选人的总票数应为814。候选人2的票数应为773。
我遇到的麻烦是找到每个候选人的票数之和,然后分别打印。我的代码仅将814和773相加,总共为1,587。
for(i = 0; i < precincts.length; i++)
{
System.out.println("How many votes were recieved in this precinct?");
numVotes[i] =scnr.nextInt();
}
for(int vote : numVotes) //Enhanced loop to copy array numVotes to vote
{
totalVotes = totalVotes + vote; //the sum of elements in numvotes to find total votes of both candidates
}
我希望我的要求对某人有意义。无论如何,谢谢您的帮助!
答案 0 :(得分:0)
您不需要两个数组即可完成此任务。您只需使用一系列区域即可满足需要。这完全取决于您如何要求用户提供输入以及您对该输入执行的操作。
您有您的precinct []数组,并且已经在 for 循环中使用了它。可以通过此循环完成所有需要获取的内容,例如:
String[] precincts = {"Precinct A", "Precinct B", "Precinct C", "Precinct D"};
int candidate1VoteSum = 0;
int candidate2VoteSum = 0;
for (int i = 0; i < precincts.length; i++) {
System.out.println("\nHow many votes were received in: " + precincts[i] + "?");
System.out.print("For Candidate 1: ");
candidate1VoteSum += scnr.nextInt();
System.out.print("For Candidate 2: ");
candidate2VoteSum += scnr.nextInt();
}
在这里,我们仅使用两个整数变量( candidate1VoteSum 和 candidate2VoteSum )来保存每个候选人的投票总数。每个区域中每个候选人的总投票额就足够了。当我们遍历区域时,我们仅要求用户提供该当前区域的每个候选人的总票数。
for 循环完成后,现在您将拥有显示投票结果所需的所有必要数据,例如:
System.out.println("\nCandidate 1 recieved a total of " +
candidate1VoteSum + " votes from all Precincts.");
System.out.println("Candidate 2 recieved a total of " +
candidate2VoteSum + " votes from all Precincts.");
System.out.println("\nThe winning Candidate is: " +
// Nested Ternary Operators are used here.
(candidate1VoteSum == candidate2VoteSum ? "It's A Tie!" :
(candidate1VoteSum > candidate2VoteSum ? "Candidate 1" : "Candidate 2"))
);
以下是有关使用Ternary Operator的信息:
如果您实际上需要将每个Precinct的总数放入一个候选数组[],那么也可以直接从 for 循环中将其添加到该数组中,但是首先您需要声明首先是整数数组,然后将其大小设置为与precincts []数组相同,因为每个元素仅持有每个Precinct的总票数,例如:
String[] precincts = {"Precinct A", "Precinct B", "Precinct C", "Precinct D"};
int[] candidate_1_Votes = new int[precincts.length];
int[] candidate_2_Votes = new int[precincts.length];
int candidate1VoteSum = 0;
int candidate2VoteSum = 0;
// Getting User input with regards to voting results...
for (int i = 0; i < precincts.length; i++) {
System.out.println("\nHow many votes were received in: " + precincts[i] + "?");
System.out.print("For Candidate 1: ");
candidate_1_Votes[i] = scnr.nextInt();
candidate1VoteSum += candidate_1_Votes[i];
System.out.print("For Candidate 2: ");
candidate_2_Votes[i] = scnr.nextInt();
candidate2VoteSum += candidate_2_Votes[i];
}
现在您有了您的候选人[] int数组(候选人_1_投票[] 和候选人_2_投票[] ),您可以确定哪个选区对任何候选人给出了总票数例如:
for (int i = 0; i < precincts.length; i++) {
System.out.println("\n" + precincts[i] + " gave Candidate 1 a total of " +
candidate_1_Votes[i] + " votes.");
System.out.println(precincts[i] + " gave Candidate 2 a total of " +
candidate_2_Votes[i] + " votes.");
}