简体   繁体   English

Java中的数字金字塔

[英]numbers pyramid in java

I am a beginner in Java programing and I want to print a pyramid like the one in the image: 我是Java编程的初学者,我想像图像中那样打印一个金字塔:

在此处输入图片说明

I already have the pyramid (without numbers) (x is the numbers of lines the users wants) Any help is good! 我已经有了金字塔(没有数字)(x是用户想要的行数)任何帮助都是好的!

for (int i=1; i<(2*x+1); i += 2)
{
    for (int k=0; k < ((x-1) - i / 2); k++)
    {
        System.out.print(" ");
    }
    for (int j=0; j<i; j++)
    {
        System.out.print(x);
    }
    System.out.println("");
}

It might be a bit simpler to write and read if you make a separate method to print each line and cell and then use an if statement to determine what to print. 如果您制作一个单独的方法来打印每行和单元格,然后使用if语句确定要打印的内容,则编写和读取起来可能会更简单一些。 The cell method encapsulates all the logic on what to print. cell方法封装了要打印的所有逻辑。

for (int i = 0; i < size; i++)
    System.out.println(line(i, size));

private String line(int row, int size) {
    StringBuilder line = new StringBuilder();
    for (int col = 0; col < size * 2 + 1; col++) {
        line.append(cell(row, col, size));
    }
    return line;
} 

or if you are using Java 8: 或者,如果您使用的是Java 8:

return IntStream.range(0, size * 2 + 1)
    .map(col -> cell(row, col, size)).collect(Collector.joining())))

Finally the method to select the character for each position: 最后是为每个位置选择字符的方法:

private String cell(int row, int col, int size) {
    int offset = size - col;
    if (offset == row)
        return "0";
    else if (offset > row)
        return " ";
    else if (row == size - 1)
        return "0";
    else
        return row;
}

Without break your existing logic, even though it is hard to read, the code can be(see the comments below): 在不破坏您现有逻辑的情况下,即使很难阅读,代码也可以是(请参见下面的注释):

        for (int i=1; i<(2*x+1); i += 2)
        {
            for (int k=0; k < ((x-1) - i / 2); k++)
            {
                System.out.print(" ");
            }
            for (int j=0; j<i; j++)
            {
                if((j==0)||(j==i-1)){
                    // if it is smallest j or biggest j, print 0
                    System.out.print(0);
                }else if(i == 2*x+1 - 2){
                    // if it is biggest i, print 0
                    System.out.print(0);
                }
                else{
                    // the rest conditions, print row number
                    System.out.print((i-1)/2);
                }
            }
            System.out.println("");
        }

All I did is replace System.out.print(x); 我所做的就是替换System.out.print(x); with

                    if((j==0)||(j==i-1)){
                        // if it is smallest j or biggest j, print 0
                        System.out.print(0);
                    }else if(i == 2*x+1 - 2){
                        // if it is biggest i, print 0
                        System.out.print(0);
                    }
                    else{
                        // the rest conditions, print row number
                        System.out.print((i-1)/2);
                    }

This is my code for getting the output 这是我获取输出的代码

for(int i=0;i<x;i++)
{
int space=x-i;
//System.out.println("inside first for");

     for(int j=0;j<(i*2)+1;j++)
     {
         int total_spaces=space;

     if(j==0 || j==(i*2))
     {
      if(j==0)
      {
         while(total_spaces>0)
         {
     System.out.print(" ");
     total_spaces--;
         }
      }

     System.out.print("0");
     if(j==(i*2))
     {
            while(total_spaces>0)
         {
     System.out.print(" ");
     total_spaces--; 
         }
     }
     }


     else
     System.out.print(i);

     }
 System.out.println();
}

Building on the answer by @haifzhan , which is an excellent answer since it gives you a solution with minimal change to the original code, it should be pointed out that the formulas can be simplified if the outer loop is also a simple zero-based increment loop. @haifzhan答案的基础上 ,这是一个很好的答案,因为它为您提供了对原始代码的最小更改的解决方案,应该指出,如果外循环也是一个简单的从零开始的增量,则可以简化公式环。

The three-way if statement can be replaced with an inline ternary expression ( ?: ), and the code can be enhanced to support pyramids up to a height of 37 by filling the interior with hex digits, as opposed to the current max height of 11. 可以用内联三元表达式( ?: :)替换三向if语句,并且可以通过用十六进制数字填充内部来增强代码以支持高达37高度的金字塔,而不是当前的最大高度。 11。

Compressing the code a bit, you get: 稍微压缩一下代码,您将得到:

for (int i = 0; i < x; i++) {
    for (int j = 0; j < x - i - 1; j++)
        System.out.print(' ');
    for (int j = 0; j <= i * 2; j++)
        System.out.print(j == 0     ||    // left edge
                         j == i * 2 ||    // right edge
                         i == x - 1 ? '0' // bottom edge
                         : Character.forDigit(i, 36)); // center hex digit
    System.out.println();
}

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

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