Skip to content
Advertisement

Java Pyramid output

Hi all I am trying to create a pyramid program that asks a user for int between 1-15. When I enter 1-9 it creates a perfect pyramid. But if I enter 10-15 the line down the middle goes to right with each number pass 10 no longer making a pyramid.

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number between 1-15");
    int dig = input.nextInt();
    for (int i = 1; i <= dig; i++) {

        for (int j = 1; j <= dig - i; j++) {
            System.out.print("   ");
        }

        for (int k = i; k >= 1; k--) {
            System.out.print("  " + k);
        }

        for (int k = 2; k <= i; k++) {
            System.out.print("  " + k);
        }
        System.out.println();
    }
}

}

Thank you for your help!

Advertisement

Answer

You can still achieve the same result with your code but rather than use the print method, use the printf method that takes a format specifier as the first parameter.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number between 1-15");
    int dig = input.nextInt();
    for (int i = 1; i <= dig; i++) {
        for (int j = 1; j <= dig - i; j++) {
            System.out.printf("%4s", " ");
        }
        for (int k = i; k >= 1; k--) {
            System.out.printf("%4d", k);
        }
        for (int k = 2; k <= i; k++) {
            System.out.printf("%4d", k);
        }
        System.out.println();
    }
}

Here each integer that is printed out is padded with additional spaces, by specifying a fixed width of 4 characters, therefore compensating for integers that can either be one or two characters long.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement