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
最好使用['StringBuilder'](HTTP://文檔.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)連接到一個'String'。 – 2012-03-05 01:28:36
確實如此,以反映更好的編程習慣。 – helloworld922 2012-03-05 01:30:51
很好的編輯。 +1 :) – 2012-03-05 01:35:09