【问题标题】:JAVA: How to combine message boxes with multiple outputsJAVA:如何将消息框与多个输出相结合
【发布时间】:2012-03-05 01:05:14
【问题描述】:

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

【问题讨论】:

    标签: java swing joptionpane


    【解决方案1】:

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

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

    【讨论】:

    • 最好使用StringBuilder,而不是连接到String
    • 正确,已更改以反映更好的编程实践。
    • 感谢 helloworld922 和@Andrew Thompson!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2015-01-02
    • 2015-05-11
    • 2013-02-28
    相关资源
    最近更新 更多