投票系统增加投票

voting system increment votes

本文关键字:增加 系统      更新时间:2023-09-26
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,值将是投票值。

如果您的投票值为 1,2,3,4 - 您可以简单地对每次投票使用以下值:

result[vote-1]++;

这个想法是你使用投票是一个正确范围内的值的事实(首先验证它!),然后你使用这个值作为数组的偏移量,并增加相关条目。