简体   繁体   English

编写一个只使用 while 循环打印数字金字塔的 Java 程序

[英]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.我有一个有效的 for 循环代码,但我无法将其转换为正确的 while 循环。

Here is the for loop code:这是for循环代码:

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循环转换for while 循环的方式:

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.您可以使用StringBuilder来保存您需要打印的整个字符串并用空格填充它。

For the initial step you set '1' into the middle and print the contents of the string.对于初始步骤,您将'1'设置为中间并打印字符串的内容。 After that you "move" to the left and right, set the next i and repeat printing until all rows are done.之后,您向左和向右“移动”,设置下一个i并重复打印,直到完成所有行。

Update更新
Added space parameter to control the distance between digits in the pyramid.添加了space参数来控制金字塔中数字之间的距离。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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