Displaying loop in JOptionPane

5.4k views Asked by At

I'm a beginner in Java programming, and I have an assignment on while loops.

The assignment was to have windows open up with the numbers 1-10 on display.

The first two, I got down. The third one was to have the user enter a number 'x', and the next window was to show all integers between 1 and 'x' using a while loop.

As I have it coded now, each loop iteration pops up in it's own window, instead of all at once, in one window.

TL;DR I want to have 1 window with 10 loops, not 10 windows with 1 loop each.

JOptionPane and while loops were in the handouts and notes he had us take, but no mention of how to combine them.

import javax.swing.JOptionPane;
public class Pr27
{
    public static void main(String[] args)
    {
        JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
        JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
        String text;
        text=JOptionPane.showInputDialog("Please enter a number: ");
        int f,x;
        f=0;
        x=Integer.parseInt(text);
        while (f<=x)
        {//What am I doing wrong between here
            JOptionPane.showMessageDialog(null, f);
            f++;
        }//and here?
    }
}
1

There are 1 answers

2
jordan dap On BEST ANSWER

I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates.

import javax.swing.JOptionPane;
public class Pr27
{
    public static void main(String[] args)
    {
       JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
        JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
        String text;
        text = JOptionPane.showInputDialog("Please enter a number: ");
        int f, x;
        //if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
        f = 1;
        x = Integer.parseInt(text);
        StringBuilder sb = new StringBuilder();
        while (f <= x)
        {
            //rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
            sb.append(f).append("\n");
            //JOptionPane.showMessageDialog(null, f);
            f++;
        }
        //string builder has a "\n" at the end so lets get rid of it by getting a substring
        String out = sb.substring(0, sb.length() - 1);
        JOptionPane.showMessageDialog(null, out);
    }
}