简体   繁体   中英

How can I print a certain string i times in a for loop?

i'm trying to print out a shape that looks something like this:

*
**
***
****
*****

To do that i'm using a for loop:

for (int i = 1; i <= 5; i++) {
  System.out.print("*");
  System.out.println;
}

but how do I get the line 2 to print i asterisks, instead of just the one asterisk as i have so far?

The logic you want to articulate here is that, for each row, print as many asterisks as the current row number. Nested loops can be used here:

for (int i=0; i < 5; i++) {       // the row
    for (int j=0; j <= i; ++j) {  // the column
        System.out.print("*");
    }
    System.out.println();
}

If you are using java 11 or greater you can use public String repeat(int count) .

for (int i = 1; i <= 5; i++) {
    System.out.println("*".repeat(i));
}

You can use

for (int i = 1; i <= 5; i++ ){
            System.out.println(new String(new char[i]).replace('\0', '*'));
}

to print * according to the value i contains each time it loops

It basically creates a new char array of size i and replaces all the nulls, ie('\0'), with * of that char array, and then it converts the char array into one single string and prints it.

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