简体   繁体   中英

JOptionPane dialog box - issue with extra lines

writing something that displays the prime numbers between 1-1000, twin primes between 1-1000, and perfect numbers between 1-10,000. not having any issues with writing those methods but the JOptionPane dialog box is driving me crazy right now. Working on trying to display 10 numbers per line for the prime numbers between 1-1000

        if( userChoice == 1 )
        {
            message = String.format( "Prime Numbers between 1-1,000 are:");
            for( number = 3; number <= 1000; number++ )
            {
                if( trueCounter % 10 == 0 )
                    message += "\n";

                prime = isPrime( number );
                if( prime == true )
                {
                    message += " " + number;
                    ++trueCounter;
                }
            }
            JOptionPane.showMessageDialog( null, message );
        }

thats what i have and it displays all the numbers and displays 10 numbers per line....but then it also displays a random number of extra lines in between so the dialog box height ends up getting way too big. and its even a set amount of extra lines which is what really confuses me... its like this

{3 5 7 11 13 17 19 23 29 31
(8 new lines)
37 41 43 47 53 59 61 67 71 73
(10 new lines..)

please help!

Change this:

            if( trueCounter % 10 == 0 )
                message += "\n";

            prime = isPrime( number );
            if( prime == true )
            {
                message += " " + number;
                ++trueCounter;
            }

To this:

            prime = isPrime( number );
            if( prime == true )
            {
                message += " " + number;
                ++trueCounter;

                if( trueCounter % 10 == 0 )
                    message += "\n";
            }

If not, you're putting a lot of newlines after the 0th, 10th, 20th, ... elements.

Om, and I would consider using StringBuilder .

I've struggled with this sort of thing. I wonder if you are having issues with word wrapping vs. carriage returns.

To test this, replace the \\n in your code with a character, like x and then see the behavior.

If you still get new lines, they may be word wraps, not \\n .

Just a guess. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM