Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java Pyramid - Using System.out.printf() to format output

Tags:

java

The Goal:

I'm attempting to produce a pyramid similar to the format given below. This requires a basic Java program that accepts user input, converts from numbers to strings, uses nested loops, and generates formatted output. Here is an example of the desired output using 8 rows.

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

The Problem:

I believe I have the logic to properly increment the numbers, however I need help with formatting the pyramid. I am able to add spaces between each number, but if the number of lines is > 10, then the formatting is messed up as you can see. On the final line (line 10), the number 1 is no longer centered. What is the reason and how can I solve this?

I know I can use System.out.printf("%4s", value), but want to find a way to do this without hard-coding in case the number of rows is > 1000. Thank you in advance for any guidance your 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:

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();
        }
    }
}
like image 962
RockyMountainCoder Avatar asked Jan 22 '18 05:01

RockyMountainCoder


People also ask

What is formatted output using printf () statement explain it?

One, the printf (short for "print formatted") function, writes output to the computer monitor. The other, fprintf, writes output to a computer file. They work in almost exactly the same way, so learning how printf works will give you (almost) all the information you need to use fprintf.

Can we use system out printf in Java?

Note: System. out. format() is equivalent to printf() and can also be used.

What is printf () in Java?

The printf() method of Java PrintStream class is a convenience method which is used to write a String which is formatted to this output Stream. It uses the specified format string and arguments to write the string.


2 Answers

Instead of hard-coding System.out.printf("%4s", value), you can build format dynamically, for example "%" + len + "s\n". This is a simpler implementation and easier to understand.

int rows = 10;  
String[] pyramid = new String[rows];
pyramid[0] = "1";
for (int row = 1; row < rows; row++) {
    pyramid[row] = (row + 1) + " " + pyramid[row - 1] + " " + (row + 1);
}

for (String line : pyramid) {
    int len = (pyramid[rows - 1].length() + line.length()) / 2;
    System.out.printf("%" + len + "s\n", line);
}
like image 95
zhh Avatar answered Oct 21 '22 11:10

zhh


I here is code for your requirement

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;

        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();
        }
    }
}
like image 2
Gnanasekaran Palanisamy Avatar answered Oct 21 '22 13:10

Gnanasekaran Palanisamy