简体   繁体   中英

Pyramid pattern in Java using for loop

I want to print the pyramid pattern using word "Stream" by using for loop in Java. Please anyone can help me with this. I have printed pyramid with "*". I have also attached the program below:

Desired Result:

                          S
                        S   t
                      S   t   r
                    S   t   r   e
                 S    t   r   e    a
              S     t   r   e    a    m

What I have so far:

public class Pyramid
{

    public static void main(String[] args)
    {

      System.out.println("-----Pyramid------");
      int n = 5;
      for (int i = 1; i <= n; i++)
      {
        for (int j = 1; j <= n - i; j++)
          System.out.print(" ");
        for (int k = 1; k <= 2 * i - 1; k++)
          System.out.print("S");
        System.out.print("\n");
      }

    }
}

You can use the charAt method in order to extract from the word Stream the chars you need inside the loop to create the pyramid

For example:

"Stream".charAt(0);

Will print the char S

"Stream".charAt(3);

Will print the char e .

More info here: String class reference

This should work with any word. As a hint I'd recommend to start loops with 0 instead of 1.

public static void main(String[] args) {
        System.out.println("-----Pyramid------");
        String word = "Stream";
        int n = word.length();
        for (int i = 0; i < n+2; i++) {
            for (int j = 0; j <= n - i; j++)
                System.out.print(" ");
            for (int k = 0; k < i - 1; k++)
                System.out.print(word.charAt(k) + " ");
            System.out.print("\n");
        }
    }

Output:

-----Pyramid------


         S 
        S t 
       S t r 
      S t r e 
     S t r e a 
    S t r e a m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM