I am learning Java and have a rather simple program that returns a series of numbers in accordance with the Collatz Conjecture. I can have it output into the console or have many JOptionPane.showMessageDialog() windows pop up, one with each number in it.
How would I combine the JOptionPane.showMessageDialog()‘s to show all the outputs in one JOptionPane.showMessageDialog()?
Code:
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.");
}
}
Thanks!
—
ZuluDeltaNiner
Keep track of the full string to be displayed, then display it at the end: