Simple java pyramid – using system out. Printf() format output
Objectives:
I am trying to generate a pyramid similar to the format given below This requires a basic Java program that accepts user input, converts numbers to strings, uses nested loops, and generates formatted output The following is an example of the required 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
Question:
I believe I have the logic to add numbers correctly, but I need help formatting the pyramid I can add spaces between each number, but if the number of lines is > 10, then you can see that the format is screwed up On the last line (line 10), the number 1 is no longer centered What is the reason and how can I solve this problem?
I know I can use system out. Printf ("% 4S", value), but you want to find a way to do this if the number of rows is > 1000 Thank you in advance for providing me with any guidance from more knowledgeable people
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:
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();
}
}
}
Solution
Here is the code for your request
import java.util.Scanner;
public class Pyramid1
{
public static void main(String[] args)
{
int i,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;
int length = ("" + rows).length();
String str = " %"+length+"s";
for (i=1; i<=rows; i++)
{
for (j=a; j>1; j--)
{
System.out.printf(str," ");
}
for (k=i; k!=0; k--)
{
String str1 = "" + k;
System.out.printf(str,str1);
}
a--;
for (int l=2; l<=i; L++)
{
String str2 = "" + l;
System.out.printf(str,str2);
}
System.out.println();
}
}
}
