【问题标题】:Java: Having trouble printing out this pyramid-like reversed number patternJava:无法打印出这种类似金字塔的倒数模式
【发布时间】:2020-10-18 22:21:32
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你做一些数学运算,而不是直接输出循环计数器,会发生什么?例如。 print((j+5-i)+" ");.

标签: java loops nested-loops


【解决方案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 

【讨论】:

  • 那些 cmets 帮助很大。我的朋友,你绝对是救生员。谢谢。
  • @Lev1athan909 - 不客气。祝你成功!
【解决方案2】:

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

有两个循环,每个循环逐行迭代。第一个从 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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多