I have programmed a working voting system, but it needs a little more decision making involved. The program needs to work if two or more candidates have the same number of votes.
Below is what i have but i think it is very long winded, and it will only work with 2 candidates having the same number of votes. Is there a more efficient way of doing this while working with 2 or more candidates having the same votes.
There are only 5 candidates available in this scenario, but should work if more are added too.
if(numArray[0] == numArray[1]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[2]);
System.out.println("And the winner is: " + Array[0] + " and " + Array[1]);
}else if(numArray[1] == numArray[2]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[1] + " and " + Array[2]);
System.out.println("And the winner is: " + Array[0]);
}else if(numArray[2] == numArray[3]){
System.out.println("\nIn third place: " + Array[2] + " and " + Array[3]);
System.out.println("In second place: " + Array[1]);
System.out.println("And the winner is: " + Array[0]);
}else{
System.out.println("\third place: " + Array[2]);
System.out.println("second place: " + Array[1]);
System.out.println("winner is: " + Array[0]);
}
I'd first check what are the scores, highest, second highest, third highest. And then pick the names which have these values
public static void displayFinalResults(String[] stringArray, int[] numArray){
int highestScore = max(numArray, Integer.MAX_VALUE);
int secondHighestScore = max(numArray, highestScore);
int thirdHighestScore = max(numArray, secondHighestScore);
System.out.println("\nIn third place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == thirdHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("In second place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == secondHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("And the winner: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == highestScore) {
System.out.println(stringArray[i]);
}
}
}
public static int max(int[] scores, int lessThan) {
int max = Integer.MIN_VALUE;
for (int score : scores) {
if (score > max && score < lessThan) {
max = score;
}
}
return max;
}