Aquiel Womble Aquiel Womble - 1 month ago 8
Java Question

Not sure how to print this?

I'm supposed to modify code that I've written for an assignment:

public class ToweringStrings2 {
public static final int H=2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}

public static void drawTowers(int H) {
for (int i=1; i<=H; i++){
System.out.print(" ");
for (int j=1; j<=i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k=1; k<=H+2; k++){
System.out.print("@");
}
System.out.println();
}
}


so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:



This is what the new code is supposed to print:


and so on.

For some reason I'm just really stuck and can't figure it out.

Answer

You can create an extra variable to print and increment

Like that:

public class ToweringStrings2 {
    public static final int H = 10; //constant for the tower

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

    public static void drawTowers(int H) {
        int count = 1;
        for (int i = 1; i <= H; i++) {
            System.out.print(" ");
            for (int j = 1; j <= i; j++) {
                System.out.print(count++ + " ");
            }
            System.out.println();
        }
        for (int k = 1; k <= H + 2; k++) {
            System.out.print("@ ");
        }
        System.out.println();
    }
}