Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing an empty square using loops

Tags:

java

loops

I need to print an empty square and my code prints this instead, and I have no idea why.

        ******
        *    *
        *    *
        *    *
        *    *
        ******

Can you explain why it's a rectangle and not a square and how can I fix it?

This is my code:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int m = 6;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= m; j++) {
                if (i == 1 || i == m)
                    System.out.print("*");
                else if (j == 1 || j == m)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            System.out.println();
        }
    }
like image 589
Mona Chatila Avatar asked May 06 '26 01:05

Mona Chatila


1 Answers

You are printing characters to text console. So if you print 6 X 6 shape, and each character is for example 5 mm X 10 mm, you get 30 mm X 60 mm shape on screen.

You can not really control this from your Java program. It would be very hard to find out the current character aspect ratio of your text console (and user can change the font at will anyway afterwards), and you can't change the font either (with Java or in platform-independent way).

Fortunately, all modern PC displays have almost square pixels. So, choose a raster font which has same width and height for characters. For example in Windows cmd.exe, below image of its Properties dialog (access from upper left corner) demonstrates one possiblity:

cmd.exe font selection dialog


If you want bigger font, then you could choose 10x20 font (width is half the height), and print extra space after each *.

Or you could choose 16x8 font (width is twice the height), and then print extra empty line between each line.

Otherwise, you can't really do it in text mode, aliasing problems will make non-integer aspect ratios look really ugly. Only way to do this "properly" is to do your own "text console" as a graphical window, where you do the text drawing so that character positions are independent of font size.

like image 179
hyde Avatar answered May 08 '26 02:05

hyde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!