简体   繁体   中英

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. 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 += "#"   //hash for square
square += "\n"  //newline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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