Page 1 of 2 12 LastLast
Results 1 to 20 of 28
  1. #1
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default Help with Array please

    okay I need to write a program that takes 5 names, votes ext... and displays them and names the winner. Also I can't get the count to work right >.<

    Java Code:
    import java.util.Scanner;
    
    
    public class Lab11
    {
    	public static void main(String[] args)
    	{
    		Scanner kb = new Scanner(System.in); // declaring/defining a Scanner object and giving it a handle to the standard input stream
    		String[] names = new String [5]; // empty string array declaration/definition, stores 5 Strings
    
    		int[] votes = new int[5]; // empty int array declaration/definition, stores 5 ints
    
    		for(int i = 0; i < 5; i++) // doing something 5 times
    		{
    			System.out.print("Enter the name of Candidate: " + (i+1) + " "); // request for input
    			names[i] = kb.nextLine(); // Scanner blocks - waits for input from user
    			System.out.print("Enter the total votes associated with Candidate: " + (i+1) + " "); // request for input
    			votes[i] = kb.nextInt(); // scanner block - waits for input from user			}
    
    		}
    
    		String winner = ""; // String data-type placeholder for the winner
    		int winnerVotes = 0; // votes the winner has
    		int totalVotes = 0; // total votes accumulated
    		int j; // declared int named j, not defined
    
    		for (j = 0; j< votes.length; j++) // doing something 5 times...
    		{
    			totalVotes += votes[j]; // summing the votes... !
    		}
    
    
    
    		System.out.println("\nCandidate Votes Received % of Total Votes");
    		System.out.println("--------- -------------- ----------------");
    
    		for (j = 0; j< names.length; j++) // doing something 5 times
    		{
    			if (votes[j]>winnerVotes) // if the vote in index j of vote array is greater than winner votes..
    			{
    				winner = names[j]; // store the name associated with the vote in the String winner
    				winnerVotes = votes[j]; // store the vote in the int winnerVotes
    			}
    
    
    	} // ^^ printing stuff out
    
    		System.out.println("Total " + totalVotes); // the total votes,
    		System.out.println("The winner of the election is " + winner); // printing out hte winner!
    	}//main
    }//election
    It complies but the exceptions are
    Java Code:
    Exception in thread "main" java.util.InputMismatchException
            at java.util.Scanner.throwFor(Scanner.java:840)
            at java.util.Scanner.next(Scanner.java:1461)
            at java.util.Scanner.nextInt(Scanner.java:2091)
            at java.util.Scanner.nextInt(Scanner.java:2050)
            at Lab11.main(Lab11.java:18)
    Press any key to continue . . .

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Is the exception thrown immediately, or when you input some data? What input caused it to be thrown? The code looks good, although I may be overlooking something.

  3. #3
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    it is thrown after I type in the 2nd name

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Scanner#nextInt doesn't consume the newline, leaving it in the buffer where it is consumed by nextLine in the second iteration of the loop. When you type the second name, that is read by nextInt and results in an input mismatch.

    db

  5. #5
    farahm is offline Member
    Join Date
    Nov 2010
    Location
    Beirut, Lebanon
    Posts
    36
    Rep Power
    0

    Default

    I checked out your code and you have a couple of minor mistakes the below code is the corrected version: (check out the comments for the corrections)
    Java Code:
    import java.util.Scanner;
    
    public class Lab11
    {
        public static void main(String[] args)
        {
            Scanner kb = new Scanner(System.in); 
            Scanner kb2 = new Scanner(System.in); //a second scanner to read the numbers
    
            String[] names = new String [5];
    
            int[] votes = new int[5]; 
            for(int i = 0; i <5; i++) 
            {
                System.out.println("Enter the name of Candidate: " + (i+1) + " "); 
                names[i] = kb.nextLine(); 
                System.out.println("Enter the total votes associated with Candidate: " + (i+1) + " ");  
                votes[i] = kb2.nextInt(); //used second scanner
            }
    
            String winner = ""; 
            int winnerVotes = 0; 
            int totalVotes = 0; 
    
            for (int j = 0; j< votes.length; j++) //no need for int j to be initialized outside
            {
                totalVotes += votes[j]; 
            }
    
            System.out.println("\nCandidate Votes Received % of Total Votes");
            System.out.println("--------- -------------- ----------------");
    
            for (int k = 0; k< names.length; k++) //different variable not int j to be used/ different variable for each loop
            {
                if (votes[k]>winnerVotes) 
                {
                    winner = names[k]; 
                    winnerVotes = votes[k]; 
                }
    
            }
    
            System.out.println("Total " + totalVotes); 
            System.out.println("The winner of the election is " + winner); 
        }
    }

  6. #6
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    Quote Originally Posted by farahm View Post
    I checked out your code and you have a couple of minor mistakes the below code is the corrected version: (check out the comments for the corrections)
    Java Code:
    import java.util.Scanner;
    
    public class Lab11
    {
        public static void main(String[] args)
        {
            Scanner kb = new Scanner(System.in); 
            Scanner kb2 = new Scanner(System.in); //a second scanner to read the numbers
    
            String[] names = new String [5];
    
            int[] votes = new int[5]; 
            for(int i = 0; i <5; i++) 
            {
                System.out.println("Enter the name of Candidate: " + (i+1) + " "); 
                names[i] = kb.nextLine(); 
                System.out.println("Enter the total votes associated with Candidate: " + (i+1) + " ");  
                votes[i] = kb2.nextInt(); //used second scanner
            }
    
            String winner = ""; 
            int winnerVotes = 0; 
            int totalVotes = 0; 
    
            for (int j = 0; j< votes.length; j++) //no need for int j to be initialized outside
            {
                totalVotes += votes[j]; 
            }
    
            System.out.println("\nCandidate Votes Received % of Total Votes");
            System.out.println("--------- -------------- ----------------");
    
            for (int k = 0; k< names.length; k++) //different variable not int j to be used/ different variable for each loop
            {
                if (votes[k]>winnerVotes) 
                {
                    winner = names[k]; 
                    winnerVotes = votes[k]; 
                }
    
            }
    
            System.out.println("Total " + totalVotes); 
            System.out.println("The winner of the election is " + winner); 
        }
    }

    I made your changes but I'm still getting the same exceptions, and its still not properly asking for the input of the names.

    Java Code:
    Enter the name of Candidate: 1 jason
    Enter the total votes associated with Candidate: 1 jm
    Exception in thread "main" java.util.InputMismatchException
            at java.util.Scanner.throwFor(Scanner.java:840)
            at java.util.Scanner.next(Scanner.java:1461)
            at java.util.Scanner.nextInt(Scanner.java:2091)
            at java.util.Scanner.nextInt(Scanner.java:2050)
            at Lab11.main(Lab11.java:19)
    Press any key to continue . . .

  7. #7
    farahm is offline Member
    Join Date
    Nov 2010
    Location
    Beirut, Lebanon
    Posts
    36
    Rep Power
    0

    Default

    After each time you enter the name or the number of votes make sure you press enter and when it says enter the number of votes you have entered "1 jm" and you are parsing a number so i will give an exception. Make sure when it asks for the name you enter a string and when it asks for a number you enter a number.
    Here is a sample of what should happen when you run the code:
    Enter the name of Candidate: 1
    farah1
    Enter the total votes associated with Candidate: 1
    12
    Enter the name of Candidate: 2
    farah2
    Enter the total votes associated with Candidate: 2
    13
    Enter the name of Candidate: 3
    farah3
    Enter the total votes associated with Candidate: 3
    14
    Enter the name of Candidate: 4
    farah4
    Enter the total votes associated with Candidate: 4
    15
    Enter the name of Candidate: 5
    farah5
    Enter the total votes associated with Candidate: 5
    2

    Candidate Votes Received % of Total Votes
    --------- -------------- ----------------
    Total 56
    The winner of the election is farah4

  8. #8
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    dhope >.< I can't run my own program lol

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I don't entirely agree with farahms changes. First, you absolutely do not need a second scanner, in fact, it's a waste. Why create a second scanner which is doing nothing that the first scanner couldn't do?

    Also, changing local loop variable names is not necessary. I can put 1000000 loops that look like this
    Java Code:
    for(int i = 0; i < 10; i++){
      Do stuff
    }
    and it will work fine.

    Disregard this, did not see you did not declare j locally, however your code was still fine since each loop will set the value of j back to 0 before running.

    Since you declared and initialized a new variable at the beginning of the loop, it will be destroyed after the loop finishes running, it will not be able to be referenced again. Because of this you don't run into problems when creating a new loop.

    I highly suggest you re read darylls post.

    When you extract something from a scanner with nextInt it gets the input and leaves the pointer just after that position, it does not swallow the rest of the line, this causes your error. Try adding this after prompting for the vote count
    Java Code:
    kb.nextLine();
    Last edited by sunde887; 04-24-2011 at 02:40 PM.

  10. #10
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    I don't entirely agree with farahms changes. First, you absolutely do not need a second scanner, in fact, it's a waste. Why create a second scanner which is doing nothing that the first scanner couldn't do?

    Also, changing local loop variable names is not necessary. I can put 1000000 loops that look like this
    Java Code:
    for(int i = 0; i < 10; i++){
      Do stuff
    }
    and it will work fine.

    Disregard this, did not see you did not declare j locally, however your code was still fine since each loop will set the value of j back to 0 before running.

    Since you declared and initialized a new variable at the beginning of the loop, it will be destroyed after the loop finishes running, it will not be able to be referenced again. Because of this you don't run into problems when creating a new loop.

    I highly suggest you re read darylls post.

    When you extract something from a scanner with nextInt it gets the input and leaves the pointer just after that position, it does not swallow the rest of the line, this causes your error. Try adding this after prompting for the vote count
    Java Code:
    kb.nextLine();
    First of all, as always I love seeing your name on here :)
    second. yea I looked at what was suggested and everything is running fine, the only question I have left is how can I line up the answers under the columns I made for them.

    such as
    name votes received % of total votes.
    Jason 5 40%
    ext....

    3rd I cannot remember how to find the percentage of an array.

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    1) thanks, I appreciate that, I enjoy helping people out where I can.

    2) If you would like to format it better you will have to use either String.format, or System.out.printf.

    I am not amazing about these and when I do use them I have to look up the flags. The general form however is
    Java Code:
    System.out.printf("%d is the number", 5);
    this will substitute d with an integer from the following arguments, in this case, 5. There are flags that can be added between the % and the d which allow a lot of formatting, including using leading spaces(which is what you want). As stated, please check the tutorials for more specifics on which flags do what.

    String.format works very similarly.

    3) you won't be finding the percentage of an array, instead you will be finding the percentage of each item in the array. If you have the total number of votes in the array you are halfway there. From there you just divide each item in the array by the total.

    Java Code:
    int[] x = {1, 6, 9, 10, 4};
    total = 30; //normally you use a loop to find the total, in this example
                    //I am adding it with my brain
    The percentage of x[0] is x[0]/total, and so on for each successive index.

  12. #12
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    so there isn't a way I could add all the numbers in each array index and then just dividing it by the total number of indexes in that array?

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,353
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by jjth39347 View Post
    so there isn't a way I could add all the numbers in each array index and then just dividing it by the total number of indexes in that array?
    Sure there is, you just have to write it yourself (a few lines at most).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Did you mean to say average votes? If so, how would you find the average of these numbers?
    Java Code:
    1 7 9 5 0 7 5 3

  15. #15
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    sorry my mistake, I asked the question wrong, I was thinking percentages not average I just ended up asking for average.

    Any way I can find percentage out of the total votes?

  16. #16
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The percentage of votes each candidate got is what I showed above, array[i]/total.

  17. #17
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    okay thank you, I've been awake for far to long lol. Hell week ya know.

  18. #18
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    gah sorry to keep bugging you, I guess my question was how do I add up all the votes?

  19. #19
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Your second loop calculates the total.

  20. #20
    jjth39347 is offline Member
    Join Date
    Feb 2011
    Posts
    71
    Rep Power
    0

    Default

    gah no more cram sessions then do home work lol.

    but I think I have it all done now

    Java Code:
    import java.util.Scanner;
    
    public class Lab11_2
    {
        public static void main(String[] args)
        {
            Scanner kb = new Scanner(System.in);
            Scanner kb2 = new Scanner(System.in); //a second scanner to read the numbers
    
            String[] names = new String [5];
    
            int[] votes = new int[5];
            for(int i = 0; i <5; i++)
            {
                System.out.println("Enter the name of Candidate: " + (i+1) + " ");
                names[i] = kb.nextLine();
                System.out.println("Enter the total votes associated with Candidate: " + (names[i]) + " ");
                votes[i] = kb2.nextInt();
    
            }
    
            String winner = "";
            int winnerVotes = 0;
            int totalVotes = 0;
    
            for (int j = 0; j< votes.length; j++)
            {
                totalVotes += votes[j];
            }
    
            System.out.println("\nCandidate Votes Received % of Total Votes");
            System.out.println("--------- -------------- ----------------");
    
            for (int k = 0; k< names.length; k++)
            {
                if (votes[k]>winnerVotes)
                {
                    winner = names[k];
                    winnerVotes = votes[k];
                }
    
            }
    
            System.out.println("% of total votes =%");
            System.out.println("The winner of the election is:" + winner+" Total number of votes:" + totalVotes+" percentage of votes: %"+(totalVotes/winnerVotes));
        }
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. convert byte array into char array
    By kgkamaraj in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 11:32 AM
  2. Replies: 23
    Last Post: 09-07-2010, 08:12 PM
  3. Replies: 2
    Last Post: 09-06-2010, 01:03 AM
  4. create a 2d char array from a 1D string array
    By jschmall12 in forum New To Java
    Replies: 1
    Last Post: 04-27-2010, 09:01 PM
  5. Replies: 1
    Last Post: 03-31-2009, 06:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •