Java Arena
Step 8 of 8

Drawing shapes with methods

Text shapes are a good workout for loops and methods together. The trick is to look at a shape one row at a time, and write down what each row is made of. Here's a pyramid of height 3:

  ^
 ^^^
^^^^^
Row Spaces Symbols
1 2 1
2 1 3
3 0 5

The spaces go down by one per row: for a height h, row r has h - r of them. The symbols go up by two: 2 * r - 1. With a method that returns repeated text, each row is then one line of code:

public class Main {
    public static void main(String[] args) {
        printPyramid(3);
    }

    public static void printPyramid(int height) {
        for (int row = 1; row <= height; row++) {
            System.out.println(repeat(" ", height - row) + repeat("^", 2 * row - 1));
        }
    }

    public static String repeat(String text, int times) {
        String result = "";
        for (int i = 0; i < times; i++) {
            result += text;
        }
        return result;
    }
}
Output
  ^
 ^^^
^^^^^

Spaces at the start of a line count, so the checks compare them exactly. (Spaces at the end of a line are ignored.)

The end of part 2

This step ends the material of the MOOC's second part. Looking back, most of it was about two tools. A loop runs the same lines as often as needed, so a program never has to repeat itself. A method gives a piece of code a name, so a long program becomes a set of small parts that can each be read and checked on its own. The shapes above use both. The MOOC closes the part with a short self-reflection questionnaire on its own site.

Your task

Challenge 1 of 3

Write printDiagonal(int size), which prints size rows with an o in each, every row one space further to the right. Use repeat for the spaces. The check runs printDiagonal(3); and expects:

o
 o
  o

Challenge 2

Write printStairs(int height), which prints stairs rising to the right. Each step is two # wide, and each row is one step longer than the one above: row r has 2 * r symbols, pushed to the right edge with spaces. The check runs printStairs(3); and expects:

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

Challenge 3

Write printDiamond(int size): a pyramid of o with size rows, followed by the same pyramid upside down without its widest row, so the diamond has 2 * size - 1 rows. The check runs printDiamond(3); and expects:

  o
 ooo
ooooo
 ooo
  o