2015-07-03 22 views
2

這是我擁有的當前代碼。它可以工作,但它會在多個對話框中輸出數字。我不知道如何在一個單獨的對話框中打印它們,並用行分隔。在單個對話框(Java)中打印數組

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

回答

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); 
+0

(int i = 0;我<= stringLength; i ++)應該是(int i = 0; i bodyjares

+0

給出一個錯誤:實際和形式參數列表的長度不同。 –

+0

for(int i = 0; i

0

你爲什麼不使用一個StringBuffer把所有的答案在一個很長的字符串(按課程的換行分隔),然後顯示它在一個對話框,當你完成?

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