Java – Printing a String in pyramid Form

javastring

I like to print a string that is got as an input from the user in a Pyramid form letter by letter.
For example – When a user gives an input as "string" then the output should be:

     s
    s t
   s t r
  s t r i
 s t r i n
s t r i n g

I've tried a small program but it doesn't arranges the words in Pyramid form. The program is

    import java.io.*;
    import java.util.Scanner;
    import java.lang.String;

    public class Mainer {
    public static void main(String args[]){
       try
       {
           Scanner sc = new Scanner(System.in);
           String s;
           int l;
           System.out.println("Enter the String : ");
           s = sc.nextLine();
           l = s.length();
           for(int i=0; i<l;i++)
           {

               for(int j=0;j<i;j++)
               {
                   System.out.printf("%c ",s.charAt(j));
               }
               System.out.printf("%c\n",s.charAt(i));
           }         

       }
       catch(Exception e)
       {
           System.err.println(e);
       }
    }
}

And the output of the above program is(when string is given as input)
Enter the String :
string

s
s t
s t r
s t r i
s t r i n
s t r i n g

Can you make it arranged as the first example?

Best Answer

So what your program needs to do is pad out the text with spaces. In your first example, your first output is actually one letter, but in the same position as the middle letter of the last output.

So the first output in pseudo-code would look something like:

String padding = (text.length/2) number of spaces;
// The padding on the left.
Print padding
// The letter to print.
Print first letter

Keep in mind that the length of the padding will change with the length of the text you are outputting in that iteration.. but I'm not going to tell you that. That would ruin all the fun :)