简体   繁体   中英

Write a java program that prints a pyramid of numbers using only a while loop

It needs to look like this:

它需要看起来像这样

I have a for loop code that works but I can't turn it into a correct while loop one.

Here is the for loop code:

public class NumPyramid {

    public static void main(String[] args) {

        int rows = 9;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= (rows - i) * 2; j++) {
                System.out.print(" ");
            }
            
            for (int k = i; k >= 1; k--) {
                System.out.print(" " + k); //create left half            
            }
            for (int l = 2; l <= i; l++) {
                System.out.print(" " + l); //create right half
            }
            
            System.out.println();
        }
    }
}

In general, this is how you convert a for loop to a while loop:

for (initial; condition; iterate) {
    statement;
}

becomes

initial;
while (condition) {
    statement;
    iterate;
}

This is what I did and it works!

  int rows = 9, i = 1;

   while (i <= rows)
    {
        int j = 1;
        while (j<=(rows-i)*2)
        {
            System.out.print(" ");
            j++;
        }
        int k = i;
        while (k >= 1)
        {
            System.out.print(" "+k);
            k--;
        }
        int l = 2;
        while (l<=i)
        {
            System.out.print(" "+l);
            l++;
        }
        System.out.println();
        i++;
    }

You may use a StringBuilder to hold the entire string you need to print and fill it with spaces.

For the initial step you set '1' into the middle and print the contents of the string. After that you "move" to the left and right, set the next i and repeat printing until all rows are done.

Update
Added space parameter to control the distance between digits in the pyramid.

int n = 9;
int i = 1;
int space = 2; // distance between two adjacent digits
int width = 2 * space * (n - 2) + 1; // 0 not included

StringBuilder sb = new StringBuilder();
while (i++ <= width) {
    sb.append(' ');  // prepare StringBuilder with whitespaces
}

i = 0;
int left = width / 2;
int right = width / 2;
while (i++ < n - 1) { // print 1..8
    sb.setCharAt(left, (char)(i + '0'));
    sb.setCharAt(right, (char)(i + '0'));
    System.out.println(sb);
    left -= space;
    right += space;
}

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