0
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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
bruh
  • 79
  • 3
  • 13

2 Answers2

3

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.

  • hey! i tried your suggestion and it really worked! thank you so much for that! but my problem now is that the output. i'm storing it in a text file and the output goes like this: candidate1 1 ( – bruh Mar 22 '15 at 17:42
  • If there is no concurrency in your app, you can manage to load the full file before a computation, then write the full data _without_ appending. But if you want to go further, you certainly need a database, like `mysql`. This is more complex but the power, flexibility and robustness is much greater than managing simple files. –  Mar 27 '15 at 09:10
0

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.

Fildor
  • 14,510
  • 4
  • 35
  • 67
amit
  • 175,853
  • 27
  • 231
  • 333