JAVA: Combining Multiple Output Message Boxes

I am learning Java and have a fairly simple program that returns a series of numbers according to the Collatz hypothesis . I can output it to the console or pop up a lot of JOptionPane.showMessageDialog() windows, one with each number in it.

How would I combine JOptionPane.showMessageDialog() to show all the outputs in one JOptionPane.showMessageDialog() ?

The 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

+4
source share
1 answer

Keep track of the full line that will be displayed, and then display it at the end:

 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); } 
+4
source

Source: https://habr.com/ru/post/1399700/


All Articles