Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a triple nested for loop to increase the length and count of the rows printed

I am curious as to how to code something like this:

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

Here is what I have tried:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i <= 8; i += 2) {
            for (int j = 0; j < i; j++) {
                System.out.print('#');
            }
            System.out.println();
        }
    }
}

This code displays:

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

But it doesn't print the lines as many times as how many characters are there.

So basically, it increments by 2, and then it displays the same amount of lines as the amount of characters inside of the loop. I cant figure this out.

What would the third nested for loop look like?

like image 242
zmiller Avatar asked Dec 04 '22 17:12

zmiller


1 Answers

This can be done with one loop using String::repeat / Collections.nCopies to create a row containing N # characters and then create N rows:

1. String::repeat
Instance method String::repeat available since JDK 11 released in September 2018

for (int i = 2; i <= 8; i += 2) {
    String row = "#".repeat(i) + "\n";
    String rows = row.repeat(i);
    System.out.print(rows);
}

2. String::join + Collections.nCopies

  • Static method String::join is available since JDK 8
  • Static method Collections::nCopies available since JDK 1.2
import static java.lang.String.join;
import static java.util.Collections.nCopies;

//...

for (int i = 2; i <= 8; i += 2) {
    String row = join("", nCopies(i, "#"));
    String rows = join("\n", nCopies(i, row));
    System.out.println(rows);
}
like image 74
Nowhere Man Avatar answered Dec 26 '22 10:12

Nowhere Man