Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Type casting error in Voting java program

  1. #1
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Type casting error in Voting java program

    Description of what the program should do:

    1. The program should allow the user to enter the last names of five candidates in a local election and
      the votes received by each candidate.
    2. The program should then output each candidate’s name, the votes received by the candidate and the percentage of the total votes received by the candidate.
    3. The program should also output the winner of the election.
    4. If the user enters a negative value for the number of votes received for a candidate then the program should set the value of vote for that candidate to zero.
    5. If the user enters a last name in small letters the program should display the surname with the first character in capitals.


    Here a Sample of Input and Output:

    ****values and names enter by the user is highlighted in green****

    Enter candidate's name and the votes received by the candidate
    Jack
    5000

    Enter candidate's name and the votes received by the candidate
    Mike
    4000

    Enter candidate's name and the votes received by the candidate
    Joe
    6000

    Enter candidate's name and the votes received by the candidate
    Robin
    2500

    Enter candidate's name and the votes received by the candidate
    Tony
    1800


    Candidate Votes Received % of Total Votes

    Jack 5000 25.906735751295333
    Mike 4000 20.72538860103627
    Joe 6000 31.088082901554404
    Robin 2500 12.953367875647666
    Tony 1800 9.32642487046632

    Total 19300

    The Winner of the Election is Joe.


    My Code so far for this task:


    import java.util.Scanner;
     
    public class voting {
     
    		public static void main(String[] args) 
     
    		{
    	    	int totalVotes = 0;
    	    	float percentOfVotes;
    	    	voting myTest = new voting();
    	        String[] enteredNames = myTest.readNames();
    	        int[] enteredVotes = myTest.readVotes();
     
    	    for ( int i=0; i < enteredVotes.length; i++ )
    	         {
    	    	   totalVotes += enteredVotes[ i ];
    	         }
    	           System.out.println("Total" + " " +  totalVotes);
     
     
    	    for( int i = 0; i < enteredVotes.length; i++)
    	         {
    	           percentOfVotes = ((enteredVotes[i]/totalVotes)*100);
     
    	           System.out.println(enteredNames[i]+ " " +  enteredVotes[i] + " " + percentOfVotes  );
    	          }
     
    	    }
     
    	    public String[] readNames()
     
    	    {
     
    	    	Scanner in = new Scanner(System.in);
    	        String names[] = new String[5];
     
    	    	        for (int i = 0; i < names.length; i++) 
    	    	        {
    	    	            System.out.println("Enter candidate's name");
    	    	            String inputWord1 = in.next();
     
    	    	            String firstLetter = inputWord1.substring(0,1);  [COLOR="Lime"]// Get first letter[/COLOR]
    	    	            String remainder   = inputWord1.substring(1);    [COLOR="Lime"]// Get remainder of word.[/COLOR]
    	    	            String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
     
    	    	            names[i] = capitalized; 
    	    	        }
    	    	       return ( names );
    	    }	
     
    	    private int[] readVotes()
    	    {
    	    int vote = 0;
     
    		    int[] votes1 = new int[5];
     
    		      for (int i = 0; i < votes1.length; i++) 
    		      {
    		      System.out.println("Enter candidate's votes");
    		      vote = EasyIn.getInt();
    		      votes1[i]= vote; 
    		      	  if (votes1[i]<0)
    		      	  {
    		      	      votes1[i]=0;
    		      	  }
    		      }    	        
    	          return ( votes1);
     
    	     }	
     
    }

    My Sample of Input and Output for my code above:

    ****values and names enter by the user is highlighted in green****

    Enter candidate's name
    Alice
    Enter candidate's name
    john
    Enter candidate's name
    petEr
    Enter candidate's name
    thomas
    Enter candidate's name
    jerry
    Enter candidate's votes
    1293
    Enter candidate's votes
    1283
    Enter candidate's votes
    -923
    Enter candidate's votes
    -128
    Enter candidate's votes
    0

    Total 2576

    Alice 1293 0.0 //having trouble with the percentage of votes recieved.
    John 1283 0.0
    Peter 0 0.0
    Thomas 0 0.0
    Jerry 0 0.0


    I have tried all that I can and now I need help for this community to fix the code.

    Thank you in advance.

    Java'88.
    Last edited by Java'88; August 18th, 2009 at 04:26 PM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    You're divinding int data types... Java is automatically truncating for you before casting it to float.

    Cast the enteredVotes[i] to float so Java will auto-cast up to float at the beginning rather than at the end.
    percentOfVotes = (((float)enteredVotes[i]/totalVotes)*100);

  3. #3
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    Okay, but what about the candidate's name and vote. As you can see I have to first ask for the names then again for the votes, which doesn't fit the description of program or the sample of how it should look like; any help on there, please .
    Last edited by Java'88; August 23rd, 2009 at 10:28 AM.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    oh, just print out only one string.
    Scanner in = new Scanner(System.in);
    for (int i = 0; i < enteredNames.length; i++)
    {
         System.out.println("Enter candidate's name and the votes received by the candidate");
         enteredNames[i] = in.nextLine();
         enteredVotes[i] = in.nextInt();
    }

    umm, i'm not sure if nextInt() will eat the newline character. If that doesn't work, try this:

    Scanner in = new Scanner(System.in);
    for (int i = 0; i < enteredNames.length; i++)
    {
         System.out.println("Enter candidate's name and the votes received by the candidate");
         enteredNames[i] = in.nextLine();
         enteredVotes[i] = in.nextInt();
         in.nextLine();
    }

  5. #5
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    I'm not really sure where I can substitute your code as I getting lots of error when I do substitute in this part of the program:

    ..........
    public String[] readNames()
     
    	    {
     
    	    	Scanner in = new Scanner(System.in);
    	        String names[] = new String[5];
     
    	    	        for (int i = 0; i < names.length; i++) 
    	    	        {
    	    	            System.out.println("Enter candidate's name");
    	    	            String inputWord1 = in.next();
     
    	    	            String firstLetter = inputWord1.substring(0,1);  // Get first letter
    	    	            String remainder   = inputWord1.substring(1);    // Get remainder of word.
    	    	            String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
     
    	    	            names[i] = capitalized; 
    	    	        }
    	    	       return ( names );
    	    }	
    ........

    Sorry for being incompetent.

  6. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    I'm effectively getting rid of the 2 helper methods you have. The reason is you can only return 1 value, but what you need is to get a candidate name and the number of votes. This is a possible solution:

    import java.util.Scanner;
     
    public class voting {
    		public static void main(String[] args) 
    		{
    	    	int totalVotes = 0;
    	    	float percentOfVotes;
    	    	voting myTest = new voting();
    	        String[] enteredNames = myTest.readNames();
    	        int[] enteredVotes = myTest.readVotes();
                    Scanner in = new Scanner(System.in);
    	        for (int i = 0; i < enteredNames.length; i++)
    	        {
    	             System.out.println("Enter candidate's name and the votes received by the candidate");
    	             enteredNames[i] = in.nextLine();
    	             enteredVotes[i] = in.nextInt();
    	        }
    	    for ( int i=0; i < enteredVotes.length; i++ )
    	         {
    	    	   totalVotes += enteredVotes[ i ];
    	         }
    	           System.out.println("Total" + " " +  totalVotes);
     
     
    	    for( int i = 0; i < enteredVotes.length; i++)
    	         {
    	           percentOfVotes = (((float)enteredVotes[i]/totalVotes)*100);
     
    	           System.out.println(enteredNames[i]+ " " +  enteredVotes[i] + " " + percentOfVotes  );
    	          }
     
    	    }
    }

    Another thing you can do is create a Candidate class, and have that store the name and number of votes. It's not really necessary in this situation, but it might be good practice especially as you progress with Java/other OOP languages to learn when and how to create effective classes for encapsulating an idea.
    Last edited by helloworld922; August 21st, 2009 at 06:43 PM.

  7. #7
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    Snice you have remove those methods what should I do with those two line of code? If I remove them I get lots of errors and if I keep them, Eclipse ask back for the method that you removed.

                    .......
    	        String[] enteredNames = myTest.readNames();
    	        int[] enteredVotes = myTest.readVotes();
                    .......

    Then there is a problem of finding the winner of the election?


    Quote Originally Posted by helloworld922

    Another thing you can do is create a Candidate class, and have that store the name and number of votes. It's not really necessary in this situation, but it might be good practice especially as you progress with Java/other OOP languages to learn when and how to create effective classes for encapsulating an idea.
    What ever way you think is the best way, I'm happy with it.

    Java'88
    Last edited by Java'88; August 23rd, 2009 at 12:23 PM.

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    lol, oops. As you learn more about programming, you'll find that it's very rare there is only 1 right answer. However, there are a lot of wrong answers

    Create an initial array to hold the names/votes:
    String[] enteredNames = new String[5];
    int[] enteredVotes = new int[5];

  9. #9
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    So far everything is good. Just finding the winner of the election is the only thing left before the program is complete. I know what is needed to find the winner of the election, but I just don't have the knowledge in java to implement my method. helloworld922 I just need a little more help .

    Thank you very much for all your help

    Quote Originally Posted by helloworld922 View Post
    lol, oops. As you learn more about programming, you'll find that it's very rare there is only 1 right answer. However, there are a lot of wrong answers
    I understand what you mean.

  10. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    I didn't want to just post the code cause then you wouldn't learn anything useful. Instead, I'll describe the thought process.

    The winner in the election is the person that has the most votes*. All you need to do is find the max of the list of number of votes. The indices of the votes match up with the name, so find which index had the most votes, then that index of the names list is the name of the winner

    If you need help finding the max, please reply, but I'd like to see what kind of algorithm and reasoning you came up with for finding the index of the highest votes.

    *Note:
    This doesn't take into account ties, but then again that makes sense. If there was to be an exact tie in an election, who one? You wouldn't be able to tell from that election alone. You'd either have to decide on some pseudo-weird way for who won (the oldest wins, tallest wins, incumbent wins, etc.), or have a re-election. This is the nice part about programming: you can shove some details away, and make assumptions, but you should have code to handle this.
    Ex: Everytime a tie is encountered, print out "There was a tie." and then quit. You can list out the names of those who tied, but that could potentially be everyone, so it's probably best to not unless you really want to or have to Also, it doesn't really matter if two losers tie, so long as at least 1 candidate had more votes. This may seem obvious, but depending on how you write your tie-checker, could fail in this case.
    Last edited by helloworld922; August 23rd, 2009 at 05:46 PM.

  11. #11
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    Quote Originally Posted by helloworld922 View Post
    I didn't want to just post the code cause then you wouldn't learn anything useful. Instead, I'll describe the thought process.

    The winner in the election is the person that has the most votes*. All you need to do is find the max of the list of number of votes. The indices of the votes match up with the name, so find which index had the most votes, then that index of the names list is the name of the winner
    Thats what I was think too, when I said "I know what is needed to find the winner of the election."

    Quote Originally Posted by helloworld922 View Post
    If you need help finding the max, please reply, but I'd like to see what kind of algorithm and reasoning you came up with for finding the index of the highest votes.
    I can find the highestvote but finding or passing the index of the max votes is what I need help with.

     
    	        for(int  vote: enteredVotes){
     
    	        	if(vote>highestVote){
    	        		highestVote=vote;
    	        		}
    	        	}	        	        
     
    	       	System.out.println("highest votes is: " + highestVote);

    Note: The initialize of the highestVote is made at the top.

  12. #12
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Voting Program

    hehe, if you want the index you can't use the special for-each loop. You've got to do this:

     for(int  i = 0; i < votes.length; i++){
     
    	        	if(votes[i]>votes[highest]){
    	        		highest = i;
    	        		}
    	        	}

    then you can do what you want with highest:
         System.out.println("The winner was " + names[highest] + " who received " + votes[highest]);

  13. The Following User Says Thank You to helloworld922 For This Useful Post:

    Java'88 (August 25th, 2009)

  14. #13
    Junior Member
    Join Date
    Aug 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My Voting Program

    Thats why I was getting that horrible error

    I was pass the value of highest vote as the index value for enteredNames but enteredNames's index only goes up to 4.

    Now the program is complete. I also solved the issue, if there was a tie in the election

    Thanks helloword922, I'm very grateful for your help.

    Java'88.
    Last edited by Java'88; August 25th, 2009 at 06:12 AM.