Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

Form a pyramid figure in Java using for loops

I'm fairly new to Java and I have to form this figure by using for loops:

    /:
   /:::
  /:::::
 /:::::::
/:::::::::

Here is my code:

      for (int row = 1; row <= 5; row++)
      {
         for (int column = 1; column <= row; column++)
         {
            System.out.print(" ");
         }
         for (int column = 1; column < row; column++)
         {
            System.out.print("/");
         }
         for (int column = 1; column < row; column++)
         {
            System.out.print(":");
         }
         for (int column = 1; column < row; column++)
         {
            System.out.print("\");
         }
         System.out.println();
      }

My code produces the following figure:

  /:
   //::\
    ///:::\
     ////::::\\

I'm not sure how to fix the spacing and reduce the amount of for loops in my code, any help/hints would be appreciated! Thank you!

question from:https://stackoverflow.com/questions/65648335/form-a-pyramid-figure-in-java-using-for-loops

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Currently you see this:

  /:
   //::\
    ///:::\
     ////::::\\

To fix the spacing, change your first loop as such:

for (int column = 1; column <= 5-row; column++)
{
  System.out.print(" ");
}

To get the right amount of colons, notice that we want a function that means the integers to the odd numbers, one function is f(n)=2n+1 and with 1-indexing, we can use f(n)=2n to fix that. You also have no need to print the sides in a loop.

Overall you should get something like this:

public class Main
{
    public static void main(String[] args) {
      for (int row = 1; row <= 5; row++)
      {
         for (int column = 1; column <= 5-row; column++)
         {
            System.out.print(" ");
         }
         System.out.print("/");
         for (int column = 1; column < 2*row; column++)
         {
            System.out.print(":");
         }
         System.out.print("\");
         System.out.println();
      }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...