I am trying to create a voting system in Java where I input the name of a candidate and the number of votes they received, then I want to be able to output the highest vote along with the name of that candidate. What I have so far is a main method that collects the names and number of votes. It puts this information into two arrays. One string array for the names, and one int array for the number of votes. I am able to calculate the highest vote by using a value method which returns the largest number in the int array. I then print the returned value without any problems but I would also like to be able to print out the name of the winner from the string array so I wanted to know was there any way I could reference the information from the string array to the int array. I need to use two separate arrays in order to complete the program. This is what I have so far
import java.util.Scanner;
public class VotingCounter1
{
public static void main(String [] args){
Scanner userInput = new Scanner(System.in);
final int SIZE = 6;
int[] votes = new int[SIZE];
String[] names = new String[SIZE];
for (int i = 0; i < names.length && i < votes.length; i++){
System.out.print("Enter candidate's name: ");
names[i] = userInput.next( );
System.out.print("Enter number of votes: ");
votes[i] = userInput.nextInt( );
}
System.out.println("And the Winner is: " + highest(votes));
}
public static int highest(int[] votes){
int high = votes[0];
for (int i = 1; i < votes.length; i++){
if (votes[i] > high){
high = votes[i];
}
}
return high;
}
}
The index of vote and candidate is same because you added into same loop . The highest vote index is the candidate of get highest vote
System.out.println("And the Winner is: " + highest(votes,names));
public static String highest(int[] votes,String names[]){
int high = votes[0];
String s= names[0];
for (int i = 1; i < votes.length; i++){
if (votes[i] > high){
high = votes[i];
s=names[I];
}
}
s=s+""+high;
return s;
}