简体   繁体   English

打印出方形格式的Java

[英]Print out square format java

I need to print out a square of hashes in the following type of format: #### #### #### #### I would like to have an input which will change the dimensions of the square based on a user's choice. 我需要以以下格式打印出一个正方形的哈希值:#### #### #### ####我想要一个输入,该输入将根据a来更改正方形的尺寸。用户的选择。 Any idea what is the best way to create a reusable method for this? 任何想法为此创建可重用方法的最佳方法是什么? My problem lies in the fact that I konw how to print a string of characters but changin this into a square leaves me baffled. 我的问题在于我知道如何打印一个字符串,但是将其更改为正方形会使我感到困惑。 Maybe I could use a loop for this as well? 也许我也可以为此使用循环?

Would this work? 这行得通吗?

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();
   }
}

Example

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

would produce 会产生

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

And

printRectangle("#", 4, 4);

would produce 会产生

####
####
####
####
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");
}

Didn't test but I hope this gives you a good enough idea. 没有测试,但我希望这能给您一个足够好的主意。

If you want to like have a string "square" that just holds all the string in one you could just instead of printing do something like. 如果您想让一个字符串“ square”仅将所有字符串都保存在一个字符串中,则可以不打印而进行类似操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM