Search code examples
javaswingjoptionpane

How to print a set of for-looped arrays in a JOptionPane?


This was my original code to print out the information entered into the program, it was designed to create a nice little table displaying tutor names on the left with their pay on the right, and the total pay of all at the bottom:

System.out.println("Tutor Stipend Report");
System.out.println("Tutors\t\tPay");
System.out.println("------\t\t---");
for(int out=0;out<numOfTutors;out++) {
    System.out.println(names[out]+"\t\t"+stipend[out]);
}
System.out.println("--------");
System.out.println("Total: " +sum);

Now I need to turn this code to display in JOptionPane and here is where I am stuck. I want to keep the same table setup as before but every time I go to display the information, lets say I need to display 3 tutors, it will just come up with 3 JOptionPane dialog boxes instead of printing the 3 tutors in one dialog box.

I realize the problem is because all the information is inside the for loop, but how do I resolve this issue so I can display the designated number of tutors and pay on one dialog box like I had with the System.out.println solution?

for (int out=0;out<numOfTutors;out++) {
    JOptionPane.showMessageDialog(null, 
                                "Tutor Stipend Report" + 
                              "\nTutors        Pay" + 
                              "\n---------         -----" + 
                              "\n"+names[out]+"               "+stipend[out] + 
                              "\n--------" + 
                              "\nTotal: " +sum);
}

Solution

  • You need to move the call to JOptionPane.showMessageDialog outside of the for-loop.

    Check out StringBuilder. It's helpful for this sort of thing:

    StringBuilder sb = new StringBuilder();
    sb.append("There are ").append(count).append(" people in the following list:\n");
    for (int i = 0; i < count; i++) {
        sb.append("Person #").append(count).append('\n');
    }
    JOptionPane.showMessageDialog(null, sb.toString());