gpt4 book ai didi

JAVA:如何将消息框与多个输出结合起来

转载 作者:搜寻专家 更新时间:2023-11-01 02:51:55 26 4
gpt4 key购买 nike

我正在学习 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.");

}

}

谢谢!

--祖鲁三角洲

最佳答案

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

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:如何将消息框与多个输出结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9560475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com