Java嵌套循环以在降序三角形中打印数字

时间:2017-03-02 23:23:01

标签: java loops

我必须编写一个嵌套的循环片段,它将具有以下输出:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

数字必须按照确切的顺序,我正在尝试使用for循环,但我无法弄清楚如何删除重复的数字。

如何使用嵌套循环实现此目的?

我目前的输出结果如下:

1
1 2
1 2 3
1 2 3 4

3 个答案:

答案 0 :(得分:3)

Nevermind, I just figured it out!

int x = 1;

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

答案 1 :(得分:0)

You want to have an external count, not base the value you're printing out on j. Thus increase the count in the nested loop every time and print that value.

答案 2 :(得分:0)

Write a code something like below. I didn't check the syntax, that is the work for you.

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