0

I need to get an integer from a user and output a pyramid with that number of levels eg. if the person entered 7 it would output

            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

the problem I'm having is keeping the 1 in the center. Can anyone figure out how to do this? Here is my code so far:

package javaapplication6;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class JavaApplication6 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of lines :");
        int num = input.nextInt();
        String output = "";
        for(int i = 1; i <= num; i++){
            output = i != 1 ? i + " " + output + " " + i : "1";
            System.out.println(output);
        }
    }
}
DomantasJ1
  • 133
  • 7

3 Answers3

1

You need to find the pattern of how number of lines affect the placing of the center.

For example if we got 3 lines :

1          #0

1 line = 0 spacing

  1        #2
2 1 2

2 lines = 2 spacing

    1      #4
  2 1 2
3 2 1 2 3

3 lines = 4 spacing

You might already see the pattern, the spacing the center piece is 2*numberOfLines.

    1      #4
  2 1 2    #2
3 2 1 2 3  #0

You will also pretty quick notice that each lines decrease with 2 in spacing. Always start with the basic things first and try to find a pattern, it makes most assignments much easier.

Rawa
  • 13,357
  • 6
  • 39
  • 55
  • ok i get how to get the ammount of spaces needed but how do i add those to the output each time the for loop runs ? – DomantasJ1 Aug 14 '14 at 20:32
1

Example:

5 lines:

0 0 0 0 1 0 0 0 0
0 0 0 2 1 2 0 0 0
0 0 3 2 1 2 3 0 0
0 4 3 2 1 2 3 4 0
5 4 3 2 1 2 3 4 0

0 = white space

You need a for loop that counts up to the given number and every time check which line you print.

If the first line every char apart from the middle is a space. So you print 4 spaces - 1 - 4 spaces.

Second line everything is space apart apart from the 3 middle chars and so on.

See the pattern? Only the middle number is 1 which is always the n-th character where n is the number of lines.

gkrls
  • 2,618
  • 2
  • 15
  • 29
1

This code should do what you Need:

package javaapplication6;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class JavaApplication6 {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of lines :");
        int num = input.nextInt();
        String output = "";
        int width= num*2-1+num*2;
        for(int i = 1; i <= num; i++){
            System.out.println(width/2-(i-1)*2);
            for (int j = 0;j<width/2-(i-1)*2;j++){
                System.out.print(" ");
            }
            output = i != 1 ? i + " " + output + " " + i : "1";
            System.out.println(output);
        }
   }
}
Jens
  • 67,715
  • 15
  • 98
  • 113