Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to make a square shape with an empty space inside something like a door, how could I improve this?

How could I improve this code? I want to print a square of asterisks with an empty space in the middle something like a door 🙂

public class Figure {
 
    public static void main(String[] args) {
        for(int i = 1; i <= 5; i++){
            for(int j = 1; j <= 7; j++){
                if(i == 3 && j == 3 || i == 3 && j == 4 ||  i == 3 && j == 5 || 
                   i == 4 && j == 3 || i == 4 && j == 4 ||  i == 4 && j == 5 ||
                   i == 5 && j == 3 || i == 5 && j == 4 ||  i == 5 && j == 5){
                    System.out.print(" ");
                }else{
                    System.out.print("*");
                }
            }
        System.out.println();
        }
    }
}

I’m trying to make a square shape with an empty space inside something like a door

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try this:

public class Figure {

    private static final int WIDTH = 7;
    private static final int HEIGHT = 5;
    private static final int MIDDLE_ROW = 3;
    private static final int MIDDLE_COL_START = 3;

    public static void main(String[] args) {
        for (int i = 1; i <= HEIGHT; i++) {
            for (int j = 1; j <= WIDTH; j++) {
                if (i >= MIDDLE_ROW - 1 && i <= MIDDLE_ROW + 1 &&
                    j >= MIDDLE_COL_START - 1 && j <= MIDDLE_COL_START + 1) {
                    System.out.print(" ");
                } else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }
}

Extract the magic numbers

The code contains several occurrences of numbers 3, 4, 5, and 7. It’s better to extract them into constants with meaningful names. For example, you could define WIDTH = 7, HEIGHT = 5, MIDDLE_ROW = 3, and MIDDLE_COL_START = 3.

Simplify the if condition

Instead of testing all 9 positions around the middle, you can use a simpler condition that checks whether the current position is inside the middle square.

Use a nested loop for the middle square:

Instead of hardcoding the positions inside the middle square, you can use a nested loop to iterate over them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading