我正在学习Java并且有一个相当简单的程序,它根据Collatz Conjecture返回一系列数字。我可以将它输出到控制台或弹出许多JOptionPane.showMessageDialog()
窗口,其中每个窗口都有一个数字。
如何合并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
答案 0 :(得分: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);
}