I would do so:
class Main {
public static void main(String[] args) {
int altura = 5;
int largura = 5;
for (int j = 0; j < largura; j++) System.out.print("* ");
System.out.print("\n");
for (int i = 2; i < altura; i++) {
System.out.print("* ");
for (int j = 2; j < largura; j++) System.out.print(" ");
System.out.print("* \n");
}
for (int j = 0; j < largura; j++) System.out.print("* ");
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
You strip what is out of the main loop pattern and avoid needlessly conditionals that makes the code more cyclomatic complexity and less efficient for generating much more processing and breaking the branch Prediction processor.
Then you make the first line in a separate loop (first for
), as well as the last one (could even create a function to not repeat the code, but for exercise effect is not necessary) which is the last one for
.
Internal lines (for
middle) you do considering the asterisk at the beginning (first print()
within that for
) and at the end of the line (last print()
within that for
) and what is variable is just the space that stays in the innermost loop that only prints space.
Of course in both row and column you count 2 less because you are doing them out of loop, so I started in 2 and not 0.
Perfect!! I was trying with an if, however I was not getting to the height-1, thank you very much!
– Ana