Hello and welcome to the Java Programming Forums.
You were very close to making this code work. I have made a few changes for you:
package test1;
import javax.swing.*;
public class Test1 {
public static int total;
public static void main(String[] args) {
int winIND;
int numCand; //number of candidates
int numVotes; //number of votes
int best = 0; //highest number of votes
int voteTotal; //total number of votes
String strName = null; //name of candidate
String strNumVote; //number of votes for each candidate
String strNumCand; // get the number of candidates from user
//get the number of candidates
strNumCand = JOptionPane.showInputDialog("Please Enter Number of Candidates: ");
numCand = Integer.parseInt(strNumCand);
int votes[] = new int[numCand];
for (int i=0; i<numCand; i++) {
strName = JOptionPane.showInputDialog("Enter Name of Candidate: ");
strNumVote = JOptionPane.showInputDialog("Please enter total number of votes: ");
votes[i] = Integer.parseInt(strNumVote);
total = total + votes[i];
if (votes[i] > best)
best = votes[i];
}
total = sumVotes(votes);
int k = winIndex(votes);
JOptionPane.showMessageDialog(null, "Total votes: " + total + " and the winner is: " + strName + " with " + best + " votes.");
}
public static int sumVotes(int a[]) {
int sum = 0;
for (int j = 0; j<a.length; j++)
{
sum += a[j];
}
return sum;
}
public static int winIndex(int votes[]) {
int winIND = 0;
for(int i = 0; i<votes.length; i++)
{
if(votes[i]>votes[winIND]);
winIND = i;
}
return winIND;
}
}
You cannot have strName[k] because you have not assigned strName as an array.
This displays total number of votes, who the winner is and how many votes they received.
If you want to display each candidate and also show their percentage then you are going to have to work this into a for loop:
JOptionPane.showMessageDialog(null, "Total votes: " + total + " and the winner is: " + strName + " with " + best + " votes.");