[英]How to make a rectangle of characters?
如何制作一个矩形的字符? 我需要让这样的图片出现在控制台中
**********
* *
* *
* *
**********
但我明白了:
*********
*********
*********
*********
*********
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;
}
}
四个角和中间的position应该是output空格,所以要判断是四个角还是中间位置,我用isFirstOrLastRow和isFirstOrLastCol来帮助判断。
这是输入 7,9 的结果
*******
* *
* *
* *
* *
* *
*******
一种非常简洁的方法,只需几行:
int a = requestNumber();
int b = requestNumber();
System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {
System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));
编辑:修正错字,现在工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.