Hello, I'm creating a simple voting program. Everything works apart from that the program wont calculate the % total of votes for each candidate. It displays each candidates percentage as 0.00%. I've tried everything to see why it does this but I'm fooled :(

import uulib.*; 

public class Candidates 
{  
    public static void main(String[] args) 
    {
        final int CandidateNo = 5;
        String[] Names = new String[CandidateNo];
        int[] Votes = new int[CandidateNo]; 
        double PercentTotal = 0;
        int Totalv = 0;
        
        for(int i = 0; i < Names.length; i=i+1)
        {
            Names[i] = Console.getString("Enter Candidate Last Name");
            Votes[i] = Console.getInt("Enter Votes for " + Names[i]);
            Totalv = Totalv + Votes[i];   
        }
        
        System.out.println("\nCandidate\t Votes Received\t\t % of Total Votes\n");
        
        for(int i = 0; i < Names.length; i=i+1)
        {
            PercentTotal = Votes[i] / Totalv * 100;  
            System.out.println(Names[i] + "\t\t" + Votes[i] + "\t\t\t" + PercentTotal);
        }
        System.out.println("\nTotal\t\t" + Totalv);
}
}

Any help will be greatly appreciated!

Cheers,
Stu.

Integer math will return an integer and integers do not have decimal places. You need to cast one of those numbers to a double while doing the division.

PercentTotal = Votes[i] / (double) Totalv * 100;

But, to tell you the truth I would probably simply make "Totalv" a double to begin with.

...
double Totalv = 0.0;
...
Totalv += Votes[i];
...
PercentTotal = Votes[i] / Totalv * 100;
...
Comments
Gotta love the int math bugs :)

Yup. Only floats (double is a double precision float) have decimal places. Integers are just that, integers, whole numbers.

In my candidate program, the user can input a string into the Names variable. As its a string they can also input numbers which I do not want them to be able to.

Is there any easy way to prevent the user typing in a number in a string variable?

Cheers,
Stu

I understand the concept of while loops but I have not come across regular expressions?

write a validation method, which checks all your input as soon as you want to input the data in the array.
what you also can do is use regex to check whether numbers occur in your String

while(input != validName(input)){
input = readString();
}
This article has been dead for over six months. Start a new discussion instead.