Making a right triangle with java is often a problem for beginners How do you guys write?
Example: When there are 5 ■ on the bottom ■ ■■ ■■■ ■■■■ ■■■■■ To be
Triangle.java
class Triangle {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print("■");
}
System.out.println();
}
}
}
Execution result.java
■
■■
■■■
■■■■
■■■■■
I think this is a common answer I haven't seen much else
Triangle.java
class Triangle {
public static void main(String[] args) {
int n = 5;
String str = "";
for (int i = 0; i < n; i++) {
str += "■";
System.out.print(str + "\n");
}
}
}
Execution result.java
■
■■
■■■
■■■■
■■■■■
Avoided nesting of for The print method also requires only one call When studying for sentences, you can intentionally nest them to move your brain, but in actual situations you want to avoid nesting.
It is faster to use StringBuilder than to add ■ with the + operator. Let's write as follows (Thank you for pointing out based on the code of @ saka1029 in the comment)
Triangle.java
class Triangle {
public static void main(String[] args) {
var n = 5;
var sb = new StringBuilder();
for (var i = 0; i < n; ++i)
System.out.println(sb.append("■"));
}
}
By the way, writing the type as var is a writing method that can be used in JDK 10 or later. Reference: [JDK 10] Type inference using var