繁体   English   中英

Java:无法打印出这种金字塔状的倒转数字模式

[英]Java: Having trouble printing out this pyramid-like reversed number pattern

我需要知道如何打印出以下模式:

5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5 
3 4 5
4 5
5

任何和所有的帮助表示赞赏。 到目前为止我所拥有的是:

for (int i = 1; i <= num; i++) 
        {
            for (int j = 1; j <= i; j++) 
            { 
                System.out.print(j+" "); 
            } 
             
            System.out.println(); 
        }
     for (int i = num-1; i >= 1; i--)
            {
                for (int j = 1; j <= i; j++)
                {
                    System.out.print(j+" ");
                }
                 
                System.out.println();
            }

它输出这个:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

所以我理解了模式本身的结构,但似乎我需要以某种方式逆转流程。 这是我不明白的。

更改循环条件,如下所示:

public class Main {
    public static void main(String[] args) {
        int num = 5;
        for (int i = num; i >= 1; i--) {// Start with num and go downwards up to 1
            for (int j = i; j <= num; j++) {// Start with i and go upwards up to num
                System.out.print(j + " ");
            }

            System.out.println();
        }
        for (int i = 2; i <= num; i++) {// Start with 2 and go downwards up to num
            for (int j = i; j <= num; j++) {// Start with i and go downwards up to num
                System.out.print(j + " ");
            }

            System.out.println();
        }
    }
}

输出:

5 
4 5 
3 4 5 
2 3 4 5 
1 2 3 4 5 
2 3 4 5 
3 4 5 
4 5 
5 

接受的答案不输出正确的模式,所以......这段代码有效。

有两个循环,每个循环逐行迭代。 第一个从 5 到 1,第二个从 2 到 5。

在每次迭代中(每行)将在第一个数字旁边打印以下数字。

int num = 5;
for(int i = num ; i > 0 ; i--){
    System.out.print(i+" "); //Print the first number of the line
    for(int j = 1; j <= num-i; j++){
    //Print as extra number as line need (first line = 0 extra numbers, 
    //second line = 1 extra number...)
        System.out.print((i+j)+" ");
    }
    System.out.println();  //New line
}
for (int i = 2; i <= num; i++) { //Print second part starting by 2
    for (int j = i; j <= num; j++) { //Print extra numbers
        System.out.print(j+" ");
    }
    System.out.println(); //New line
}

输出符合预期:

5 
4 5 
3 4 5 
2 3 4 5 
1 2 3 4 5 
2 3 4 5 
3 4 5 
4 5 
5 

暂无
暂无

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

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