Results 1 to 10 of 10
  1. #1
    turbopenguin is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Printing multiple arrays in 1 dialog box

    Hey everyone, new here and am having a bit of trouble on this java program.

    I need the program to read in 5 candidates from the user (string array), how many votes they got (also user entered and an int array), calculate the % of votes they received (double array), and figure out who the winner is and display the results in a dialog box. Everything is working accordingly except the last part where I need to print the results to a GUI. I can only get one array (the candidates one) to appear in the dialog box.
    The format should look like this:

    candidate's name \t Votes received \t % of votes



    Java Code:
    package arraygui;
    
    import java.util.Scanner;
    import java.io.*;
    import javax.swing.*;
    
    /**
     *
     * @author Tommy
     */
    public class ArrayGUI {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
              Scanner keyboard = new Scanner (System.in);//initialize keyboard as new input device
            
            //3 arrays initialized
            String[] candidates = new String[5];
            int[] votes = new int[5];
            double[] percentage = new double[5];
            
            //declare variables
            int i=0;
            int total=0;
            int maxIndex;
            String winner;
            String outputstr;
            
            
            for(i=0; i<candidates.length; i++)//for loop that asks user to input candidates name and how many votes they received
            {
                System.out.println("Enter Candidate's Name");    
                candidates[i] = keyboard.next();
                System.out.println("How many votes did " +candidates[i] +" receive?");
                votes[i] = keyboard.nextInt();
                percentage[i] = votes[i]; //copies value in votes array to percentage array for calculation later on
                
            }
                  
          for(int index = 0; index<votes.length; index++)//for loop goes through the votes array and totals all the votes into 1 variable
              total = total + votes[index];
          
          for(int index = 0; index<percentage.length; index++)//for loop goes through percentage array and calculates percentage of votes for corresponding candidate
              percentage[index] = (percentage[index]/total)*100;
          
          maxIndex = 0;
          
          for(int index = 1; index < votes.length; index++) //for loop goes through votes array and determines the candidate with the highest # of votes
              if(votes[maxIndex] < votes[index])
                  maxIndex = index;
          
          winner = candidates[maxIndex];
          
          JOptionPane.showMessageDialog(null, "The candidate" +candidates +"The votes" +votes, "Printing Results", JOptionPane.INFORMATION_MESSAGE);
          //if I take away the  [+"The votes" +votes] and just leave the candidates there it will print that fine, but if I try it like this 
          //the dialog box will come up and spit a bunch of random numbers. 
          
          
            
        }
    }
    My question is how to I print these 3 arrays in 1 dialog box?

  2. #2
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    You need to concatenate (sum) the string statements together with a new line at the end of each string statement. That new string can then be passed to the JOptionPane.

  3. #3
    turbopenguin is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    Wouldn't all the arrays need to be of the same type in order to do that?

  4. #4
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    No, the string object automatically converts them to a String type.

  5. #5
    turbopenguin is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    at the end of each string statement; where exactly do you mean by that. At the end of the for loops I have set up? or after all the for loops?

  6. #6
    Moojaki is offline Member
    Join Date
    Apr 2012
    Posts
    1
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    So, I believe the issue is you are attempting to concat (via the '+' operator) the base array (i.e. candidates). I believe you need to get the individual elements of each array, and fold each of those into your overall string. Here is a quick example of what I am talking about:

    Java Code:
    import javax.swing.*;
    
    public class testSwing {
    	public static void main(String[] args) {	
    	
    		Integer array1[] = {1, 2, 3, 4};
    		Double array2[] = {1.0, 2.0, 3.0, 4.0};
    		String array3[] = {"str1", "str2", "str3"};
    		
    		StringBuilder tempStr = new StringBuilder();
    		
    		// get elements of array1
    		for (Integer i = 0; i < array1.length; i++) {			
    			tempStr.append("array1[" + i + "]: " + array1[i] + "\n");					
    		}
    		
    		tempStr.append("\n");
    		
    		// get elements of array2
    		for (Integer i = 0; i < array2.length; i++) {
    			tempStr.append("array2[" + i + "]: " + array2[i] + "\n");
    		}
    		
    		tempStr.append("\n");
    		
    		// get elements of array3
    		for (Integer i = 0; i < array3.length; i++) {
    			tempStr.append("array3[" + i + "]: " + array3[i] + "\n");
    		}
    	
    		JOptionPane.showMessageDialog(null, tempStr.toString());
    	}
    }

  7. #7
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    I was thinking of something more of like this:

    Java Code:
          String All = "";
          for (int k = 0; k<2; k++)
          {
              All += "The candidate " +candidates[k] + " The votes " +votes[k]+"\n";
          }

  8. #8
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    The "All" should be "all" and the loop should go 5 and not 2.

  9. #9
    turbopenguin is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    OH HAPPY DAY! it works! Mooj I tried your method and it seemed to cause a memory overload error lol. Shall, thanks a ton I really appreciate it. So, correct me if I'm wrong, but essentially we created a new string called "all" and then simply copied each array into it line by line? It almost makes too much sense. Here's the (almost) finished code if anyone's interested. I'm just having some irritating formatting problems now. It never ends!




    Java Code:
    package arraygui;
    
    import java.util.Scanner;
    import java.io.*;
    import javax.swing.*;
    
    /**
     *
     * @author Tommy
     */
    public class ArrayGUI {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
              Scanner keyboard = new Scanner (System.in);//initialize keyboard as new input device
            
            //3 arrays initialized
            String[] candidates = new String[5];
            int[] votes = new int[5];
            double[] percentage = new double[5];
            
            //declare variables
            int i=0;
            int total=0;
            int maxIndex;
            String winner;
            String outputstr;
            
            
            for(i=0; i<candidates.length; i++)//for loop that asks user to input candidates name and how many votes they received
            {
                System.out.println("Enter Candidate's Name");    
                candidates[i] = keyboard.next();
                System.out.println("How many votes did " +candidates[i] +" receive?");
                votes[i] = keyboard.nextInt();
                percentage[i] = votes[i]; //copies value in votes array to percentage array for calculation later on
                
            }
                  
          for(int index = 0; index<votes.length; index++)//for loop goes through the votes array and totals all the votes into 1 variable
              total = total + votes[index];
          
          for(int index = 0; index<percentage.length; index++)//for loop goes through percentage array and calculates percentage of votes for corresponding candidate
              percentage[index] = (percentage[index]/total)*100;
          
          maxIndex = 0;
          
          for(int index = 1; index < votes.length; index++) //for loop goes through votes array and determines the candidate with the highest # of votes
              if(votes[maxIndex] < votes[index])
                  maxIndex = index;
          
          winner = candidates[maxIndex];
          
          
          String all = "";
    for (int k = 0; k<5; k++)
    {
        all += candidates[k]+"   " + votes[k]+"   "+ "%.2f"+percentage[k]+"\n"; //I try \t instead of the spaces but it doesnt pick up, so the format is a bit messy. 
    }
    
     JOptionPane.showMessageDialog(null, "Candidate      Votes Received      % of Votes Received\n"+all+ "\nThe winner is "+winner, "shababa", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    Now I can't seem to figure out how to format the percentage array to 2 decimal places. that %.2f in there now just shows up in the output, and put a \t in between each value in the output so it looks like this
    candidate "\t" votes "\t" % votes
    john "\t" 50 "\t" 95.59
    Last edited by turbopenguin; 04-19-2012 at 07:44 AM.

  10. #10
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Printing multiple arrays in 1 dialog box

    You should use the String format member function.

    See "Format String Syntax" at Formatter (Java 2 Platform SE 5.0). It will show String format member function example.

Similar Threads

  1. Replies: 8
    Last Post: 09-12-2011, 02:43 PM
  2. Replies: 3
    Last Post: 03-22-2010, 02:50 AM
  3. Replies: 0
    Last Post: 03-10-2010, 03:13 AM
  4. Printing (no dialog)
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-04-2008, 10:36 AM
  5. Multiple Line Input Dialog Box
    By johnt in forum AWT / Swing
    Replies: 2
    Last Post: 05-31-2007, 10:30 PM

Posting Permissions

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