2012-03-05 35 views
4

我正在學習Java,並有一個相當簡單的程序,返回一系列符合Collatz Conjecture的數字。我可以將它輸出到控制檯或彈出多個JOptionPane.showMessageDialog()窗口,每個窗口都有一個。JAVA:如何組合消息框與多個輸出

我該如何結合JOptionPane.showMessageDialog()的顯示所有的輸出在一個JOptionPane.showMessageDialog()

代碼:

package collatz; 

import java.util.Random; 
import javax.swing.*; 

public class Collatz { 

/** 
* Demonstrates the Collatz Cojecture 
* with a randomly generated number 
*/ 

public static void main(String[] args) { 
    Random randomGenerator = new Random(); 
    int n = randomGenerator.nextInt(1000); 

    JOptionPane.showMessageDialog(null, "The randomly generated number was: " + n); 


    while(n > 1){ 
     if(n % 2 == 0){ 
      n = n/2; 
      JOptionPane.showMessageDialog(null, n); 
     } 
     else{ 
      n = 3 * n + 1; 
      JOptionPane.showMessageDialog(null, n); 
     } 
    } 

    JOptionPane.showMessageDialog(null, n); 
    JOptionPane.showMessageDialog(null, "Done."); 

} 

} 

謝謝!

- ZuluDeltaNiner

回答

4

跟蹤滿弦的要被顯示,則在結束顯示它:

public static void main(String[] args) { 
    Random randomGenerator = new Random(); 
    int n = randomGenerator.nextInt(1000); 

    StringBuilder output = new StringBUilder("The randomly generated number was: " + n + "\n"); 

    while(n > 1){ 
     if(n % 2 == 0){ 
      n = n/2; 
     } 
     else{ 
      n = 3 * n + 1; 
     } 
     output.append(n + "\n"); 
    } 

    output.append("Done."); 
    JOptionPane.showMessageDialog(null, output); 

} 
+1

最好使用['StringBuilder'](HTTP://文檔.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)連接到一個'String'。 – 2012-03-05 01:28:36

+0

確實如此,以反映更好的編程習慣。 – helloworld922 2012-03-05 01:30:51

+0

很好的編輯。 +1 :) – 2012-03-05 01:35:09