if (vote1 == 1) {
result[0] = result[0] + 1;
i.println(pres1 + " " + result[0]);
}
我的 if 语句最多为 4 个(例如:else if (vote1==2...3...4)
)。每次我选择多个候选人时,结果都会出错,有时,输出会改变。我希望每次我选择候选人 1 时,他的选票都会增加,并且当我选择其他候选人时,输出不会发生任何变化。
例如:
candidate 1 = 8 (and increment)
candidate 2 = 3 (and increment)
candidate 3 = 5 (and increment)
candidate 4 = 6 (and increment)
请有人帮助我,我的项目真的需要它
最佳答案
如果您需要增加多个候选人的投票,则需要某种循环来更新每个候选人的投票:
int nbCandidates = 4;
int[] result = new int[nbCandidates];
// assuming you want to increment candidate 1, 3 and 4
// contained in an array
int[] candidatesToUpvote = {1,3,4};
for (int c : candidatesToUpvote) {
result[c-1] += 1;
}
这里我假设候选者由 [1,4] 之间的数字标识。由于 Java 中数组索引从 0 开始,因此必须使用 (id - 1)
将 id 转换为索引。 。
有更强大的解决方案 HashMap<Integer, Integer>
其中键是候选人 id,值是投票值。
关于java - 投票系统增加票数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060651/