簡體   English   中英

打印出方形格式的Java

[英]Print out square format java

我需要以以下格式打印出一個正方形的哈希值:#### #### #### ####我想要一個輸入,該輸入將根據a來更改正方形的尺寸。用戶的選擇。 任何想法為此創建可重用方法的最佳方法是什么? 我的問題在於我知道如何打印一個字符串,但是將其更改為正方形會使我感到困惑。 也許我也可以為此使用循環?

這行得通嗎?

public void printRectangle(String str, int width, int height) {
   for (int y=0; y<height; y++) {
       for (int x=0; x<width; x++) {
           //if (x > 0) System.out.println(" ");
           System.out.print(str);
       }
       System.out.println();
   }
}

printRectangle("#### ", 4, 4);

會產生

#### #### #### ####
#### #### #### ####
#### #### #### ####
#### #### #### ####

printRectangle("#", 4, 4);

會產生

####
####
####
####
int size_of_square = 4;
for(int i = 0; i < size_of_square; i++){
    for(int j = 0; j < size_of_square; j++){
        System.out.print("#");
    }
    System.out.print("\n");
}

沒有測試,但我希望這能給您一個足夠好的主意。

如果您想讓一個字符串“ square”僅將所有字符串都保存在一個字符串中,則可以不打印而進行類似操作。

square += "#"   //hash for square
square += "\n"  //newline

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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