簡體   English   中英

如何制作一個矩形的字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM