bruh
bruh

Reputation: 79

voting system increment votes

if (vote1 == 1) {
    result[0] = result[0] + 1;
    i.println(pres1 + " " + result[0]);
}

my if statement are up to 4 (eg: else if (vote1==2...3...4)). every time i choose multiple candidates, the result will get wrong and sometimes, the output will change. i want that every time i choose candidate 1, his votes will increment and also when i choose other candidates without any changes in the output.

eg:

candidate 1 = 8 (and increment)
candidate 2 = 3 (and increment)
candidate 3 = 5 (and increment)
candidate 4 = 6 (and increment)

please can someone help i really need it for my project

Upvotes: 0

Views: 872

Answers (2)

user4673105
user4673105

Reputation:

If you need to increment for multiple candidates, you need some sort of a loop to update the vote of each candidate:

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;
}

Here I assume that the candidate is identified by a number between [1,4]. Since array indexes start at 0 in Java, you have to translate from id to index with (id - 1).

There are more robust solutions with a HashMap<Integer, Integer> where the key is the candidate id, and the value will be the vote value.

Upvotes: 3

amit
amit

Reputation: 178521

If your vote is value from 1,2,3,4 - you can simply use the following for each vote:

result[vote-1]++;

The idea is you use the fact that vote is a value in the correct range (verify it first!), and then you use this value as an offset of your array, and increment the relevant entry.

Upvotes: 0

Related Questions