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
>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.