在单个对话框中打印数组(Java)

时间:2015-07-03 18:31:20

标签: java arrays joptionpane

这是我目前的代码。它可以工作但它会在多个对话框中输出数字。我不知道如何在单个对话框中打印它们,用线分隔。

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
            }
    }
}

3 个答案:

答案 0 :(得分:2)

更正此代码段:

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

String out="";

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

答案 1 :(得分:1)

当您可以直接显示输出时,不确定为什么需要额外的loop

public class SecondClass {

    public static void main(String args[]) {
        String value = JOptionPane.showInputDialog(null, "Input numbers",
                JOptionPane.QUESTION_MESSAGE); // input
        JOptionPane.showMessageDialog(null, "You entered " + value, "Value",
                JOptionPane.INFORMATION_MESSAGE); // output box
    }
}

圈版:

public class SecondClass {

    public static void main(String args[]) {
        char num[];
        String value = JOptionPane.showInputDialog(null, "Input numbers",
                JOptionPane.QUESTION_MESSAGE); // input
        num = value.toCharArray(); // assigning each character to array num[]
        final StringBuilder builder = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            builder.append(num[i]);

        }
        JOptionPane.showMessageDialog(null, "You entered " + builder, "Value",
                JOptionPane.INFORMATION_MESSAGE); // output box
    }
}

答案 2 :(得分:0)

为什么不使用StringBuffer将所有答案放在一个长字符串中(当然是用换行符分隔),然后在完成后在对话框中显示它?