如何制作一个矩形的字符?我需要在控制台中显示这样的图片
**********
* *
* *
* *
**********
但是我明白了:
*********
*********
*********
*********
*********
从控制台输入a和b边。
int a = requestNumber();
int b = requestNumber();
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
if (j == 0 || j < (b - 1))
System.out.print("*");
else {
System.out.print(" ");
}
}
System.out.println();
}
}
public class Rectangle {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.printRectangle(7,9);
}
private void printRectangle(int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
|| !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
System.out.print(" ");
}
else {
System.out.print("*");
}
}
System.out.println();
}
}
private boolean isFirstOrLastRow(int currentRow, int row) {
return currentRow == 0 || currentRow == row - 1;
}
private boolean isFirstOrLastCol(int currentCol, int col) {
return currentCol == 0 || currentCol == col - 1;
}
}
[四个角和中间位置应该输出空格,所以我们应该判断是四个角还是中间位置,我使用isFirstOrLastRow和isFirstOrLastCol来帮助判断。
这是inout 7,9的原因
*******
* *
* *
* *
* *
* *
*******