Returning text built in a loop
A method can build a String in a loop and return it. Start from the empty String "", and add a piece in each round with +=:
public class Main {
public static void main(String[] args) {
System.out.println(dashes(5));
System.out.println("[" + dashes(3) + "]");
System.out.println("[" + dashes(0) + "]");
}
public static String dashes(int count) {
String line = "";
for (int i = 0; i < count; i++) {
line += "-";
}
return line;
}
}
-----
[---]
[]Returning the text, instead of printing it, means the caller can put it anywhere: on a line of its own, between brackets, or in front of other text on the same line. The next step uses exactly that to draw shapes.
(Java has a ready-made way to do this, "-".repeat(5). Here the point is the loop, so the challenges ask you to write it yourself.)