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?
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 20182.
String::join
+Collections.nCopies
String::join
is available since JDK 8Collections::nCopies
available since JDK 1.2