简体   繁体   English

用数字打印反三角-Java

[英]Printing Reverse Triangle with Numbers - Java

I have some problem printing a reverse triangle I want to achieve, like this pattern: 我在打印要实现的反向三角形时遇到一些问题,例如这种模式:

******
***
*

But my goal is to achieve that pattern with this numbers : 但是我的目标是通过以下数字实现该模式:

333221
221
1

So, this is my code so far: 所以,这是我到目前为止的代码:

int x = 1;
for(int r=0;r<3;r++)
{
    x=x+r;
    for(int c=0;c<x;c++)
    {
        System.out.print("*");
    }
    x+=1;
    System.out.println();
}

Which the output is upright like this: 其输出是直立这样的:

*
***
******

I want to make the pattern reverse with the numbers as it shown above. 我想用上面显示的数字使图案反转

Can anyone give me some idea how to deal with it? 谁能给我一些如何处理的想法? Thanks! 谢谢!

This is how i would do it: 这就是我要怎么做:

    for (i = 3; i > 0; i--) {

        for (j = i; j > 0; j--) {

            for (c = j; c > 0; c--) {

                System.out.print(j);
            }
        }
        System.out.println();

    }
  • first loop: you want to print 3 lines; 第一循环:要打印3行;
  • second loop: each line has i distinct numbers 第二循环:每行有我不同的数字
  • third loop: print number jj times 第三循环:打印次数jj次

You just need to reverse the order of your loops and decrement x instead of incrementing it. 您只需要反转循环的顺序并递减x,而不是递增即可。 I change the code a bit though : 我虽然更改了一些代码:

int level = 3;
for(int r=level ; r>0 ; r--) {
    for(int c=r ; c>0 ; c--) 
        for (int x=0 ; x<c ; x++)
            System.out.print("*");
    System.out.println();
}
        int depth = 3;
        for (int r = depth + 1; r >= 0; r--) {
            for (int c = 0; c < r; c++)
                for (int b = 0; b < c; b++)
                    System.out.print("*");
            System.out.println();
        }
@Test
public void reverseTriangle(){
    int num = 3;
    for (int i = num; i > 0; i--) {
        this.draw(i);
        System.out.println();
    }
}

private void draw(int num) {
    int total = 0;
    for (int i = 0; i <= num; i++) {
        total = total + i;
    }
    for (int i = 0; i < total; i++) {
        System.out.print("*");
    }
}

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

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