Java Arena
Step 7 of 8

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;
    }
}
Output
-----
[---]
[]

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.)

Your task

Challenge 1 of 3

Write a method repeat(String text, int times) that returns text repeated times times. The check runs System.out.println(repeat("ab", 3)); and expects:

ababab

Challenge 2

Write printStripes(int width, int rows), which prints rows lines, each width characters long. The lines take turns: = first, then -, then = again, and so on. Use the repeat method that's already there. The check runs printStripes(5, 3); and expects:

=====
-----
=====

Challenge 3

Write printFrame(int width, int height), which prints a frame of #: the top and bottom lines are full, and the lines between have a # at each end with spaces between. Width and height are always at least 2. Use repeat. The check runs printFrame(5, 4); and expects:

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