Alex Rivera | Logout

I can't wrap my head around the "draw some stairs with stick-men" program

Asked 2012-07-23T07:13:24.580
26

You've probably seen it before in a Java 1 class: it's a problem that asks you write a program that draws the following figure:

enter image description here

I have to use a constant. I am not allowed to use anything but for-loops, print, and println. No parameters, no arrays. I know how I could do it with parameters and arrays, lucky me. Any help is appreciated!

Here is my incomplete code:

public class Stairs {
    public static final int LENGTH=5;

    public static void main(String[] args) {
        printStairs();
    }

    public static void printStairs() {
        for (int allStairs=1; allStairs<=15; allStairs++) {
            for (int spaces=1; spaces<=(-5*allStairs+30); spaces++) {
                System.out.print(" ");
            }
            for (int stair = 1; stair <= 5; stair++) {
                System.out.println("  o  *******");

            }
        }
    }
}
Edit
Report

1 Answer

3

Here is my final final attempt using formatting.

public static void main(String[] args) {
    int steps = 5;
    for (int x = 0; x < steps; x++) {
        System.out.format(((steps == (x + 1)) ? "" : ("%"
                + ((steps - x - 1) * 5) + "s"))
                + "  o  ******"
                + ((x == 0) ? "" : ("%" + (x * 5) + "s"))
                + "*\n", " ", " ");
        System.out.format(((steps == (x + 1)) ? "" : ("%"
                + ((steps - x - 1) * 5) + "s"))
                + " /|\\ *     "
                + ((x == 0) ? "" : ("%" + (x * 5) + "s"))
                + "*\n", " ", " ");
        System.out.format(((steps == (x + 1)) ? "" : ("%"
                + ((steps - x - 1) * 5) + "s"))
                + " / \\ *     "
                + ((x == 0) ? "" : ("%" + (x * 5) + "s"))
                + "*\n", " ", " ");
    }
    for (int i = 0; i < (steps + 1) * 5 + 2; i++) {
        System.out.print("*");
    }
}

Output:

                      o  *******
                     /|\ *     *
                     / \ *     *
                 o  ******     *
                /|\ *          *
                / \ *          *
            o  ******          *
           /|\ *               *
           / \ *               *
       o  ******               *
      /|\ *                    *
      / \ *                    *
  o  ******                    *
 /|\ *                         *
 / \ *                         *
********************************

\o/

The approach below is also funny (depending on your humor preferences), but not a complete solution:

    for (String s = "                           o  *****                          /|\\ *                              / \\ *    "; s
            .charAt(8) != '*'; s = s.substring(5, s.length() / 3) + "     "
 
answered 2012-07-23T09:57:41.213

Your Answer