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 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
String::join
is available since JDK 8Collections::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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With