Purpose:
I am trying to create a pyramid similar to the format below. This requires a basic Java program that accepts user input, converts from numbers to strings, uses nested loops, and generates formatted output. The following is an example of the desired output using 8 lines.
Enter the number of lines: 8 1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
Problem:
I believe that I have the logic to properly increase the numbers, however I need help in formatting the pyramid. I can add spaces between each number, but if the number of lines is> 10, the formatting is messed up, as you can see. On the last line (line 10), number 1 is no longer centered. What is the reason and how can I solve this?
I know that I can use System.out.printf ("% 4s", value), but I want to find a way to do this without hard coding if the number of lines is> 1000. Thanks in advance for any guidance that much more knowledgeable minds can give me. .
1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
My current code is:
import java.util.Scanner; public class Pyramid1 { public static void main(String[] args) { int i, j, k, a; //Create a Scanner object Scanner input = new Scanner (System.in); //Prompt the user to enter number of rows in pyramid System.out.print("Enter number of rows: "); int rows = input.nextInt(); a = rows; //Logic for (i=1; i<=rows; i++) { for (j=a; j>1; j--) { System.out.printf(" %s", " "); } for (k=i; k!=0; k--) { String str1 = "" + k; System.out.printf(" %s", str1); } a--; for (int l=2; l<=i; l++) { String str2 = "" + l; System.out.printf(" %s", str2); } System.out.println(); } } }
java
TheNoviceCoder
source share