如何打印完整的金字塔图案?

时间:2017-12-23 19:21:43

标签: android eclipse

我的预期输出

enter image description here

我尝试了以下代码,但它只打印了一个*。我很困惑代码出错了。                 int rows = 6,k = 0;

            for(int i = 1; i <= rows; ++i, k = 0) {
                for(int space = 1; space <= rows - i; ++space) {
                    t2.setText("  ");
                }

                while(k != 2 * i - 1) {
                    t2.setText("* ");
                    ++k;

                }
                t2.setText();

            }

3 个答案:

答案 0 :(得分:1)

试试这个:

```

Scanner sc = new Scanner(System.in);
   char s;
   int l;
   System.out.println("Enter the Letter : ");
   s = sc.next().charAt(0);
   l = Character.getNumericValue(s)-9;
   for (int i = 0; i < l; i++) 
   {
        for (int j = 0; j < (l - i); j++) 
            System.out.print(" ");
        for (int j = 0; j <= i; j++) 
            System.out.printf("%c%s",(char)j+65,"");
        for (int j = i; j > 0; j--) 
            System.out.printf("%c%s",(char)j+64,"");    
        System.out.println();             
   }

```

答案 1 :(得分:1)

这会像魅力一样......

int y = 5,x = 5;

for (int i = 0; i < y; i++)
{
    for (int j = 0; j < x-i; j++)
    {
        System.out.print(" ");
    }

    for (int k = 0; k < i+1; k++)
    {
        System.out.print("* ");
    }


    System.out.print("\n");
}

答案 2 :(得分:1)

OP可以称之为:

String s = createCharPyramid(5, "*");
t2.setText(s);

并定义此方法:

private String createCharPyramid(int numberOfRows, String mySymbol){
    String s = "";
    String sep = System.lineSeparator();
    for(int i = 0; i < numberOfRows; i++){
        for(int j = 0; j < (numberOfRows - i); j++){
            s = s + " ";
        }
        for(int j = 0; j <= i; j++){
            s = s + mySymbol;
        }
        for(int j = i; j > 0; j--){
            s = s + mySymbol;
        }
        s = s + sep;
    }

    return s;
}

这个答案基于MrRobot的回答。他的回答是纯粹的java解决方案,并且会在控制台中正确显示金字塔。所以,如果你喜欢这个答案,请给他一个+1。