Search code examples
javaarraysjoptionpane

Printing an array in a single dialog box (Java)


This is the current code I have. It works but it would output the numbers in multiple dialog boxes. I don't have any idea how I should print them in a single dialog box, separated by lines.

import javax.swing.JOptionPane;

public class SecondClass
{
    public static void main (String args[])
    {

        int stringLength;
        char num[];


        String value = JOptionPane.showInputDialog (null, "Input numbers", JOptionPane.QUESTION_MESSAGE); //input
        stringLength = value.length(); //getting string length and converting it to int
        num = value.toCharArray(); //assigning each character to array num[]


            for (int i = 0; i <= stringLength; i++) {
                JOptionPane.showMessageDialog (null, "You entered " + num[i] , "Value", JOptionPane.INFORMATION_MESSAGE); //output box
            }
    }
}

Solution

  • Correct this snippet:

     for (int i = 0; i <= stringLength; i++) {
                    JOptionPane.showMessageDialog (null, "You entered " +
                     num[i] , "Value", 
                     JOptionPane.INFORMATION_MESSAGE); //output box
     }
    

    To

    String out="";
    
     for (int i = 0; i < stringLength; i++) {
                    out+= "You entered " + num[i] ;
     }
     JOptionPane.showMessageDialog (null, out, "Value\n", JOptionPane.INFORMATION_MESSAGE);