投票系统增量选票

voting system increment votes

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)

有人可以帮助我的项目吗

如果您的投票值来自 1、2、3、4 - 您可以简单地为每票使用以下内容:

result[vote-1]++;

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

如果您需要增加 多个 候选人,您需要某种循环来更新每个候选人的投票:

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,值将是投票值。