JAVA:如何将消息框与多个输出组合在一起

我正在学习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

解决方法:

跟踪要显示的完整字符串,然后在结尾显示:

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

}
上一篇:java – 如何表示一个垂直的showOptionDialog按钮


下一篇:java – 如何从菜单栏打开新窗口?