下降输出中的三角形

j g*_*j g -2 java loops

为什么输出在3之后进入新线?像这样:

9

8 7

6 5 4

3

2 1

我输入的任何数字总是在3之后输入一个新行.当我输入9时,我的目标输出应该是这样的:

9

8 7

6 5 4

3 2 1 0

请您澄清为什么3号后进入新线?

public class TriangleWithInput {

/**
 * @param args
 */
@SuppressWarnings("resource")
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int input = sc.nextInt();

    while (input >= 0) {
        int c = 1;
        while ( c <= input) {
            int r = 1;
            while (r <= c) {
                System.out.print(input + " ");
                input--;
                r++;
            }
            System.out.println();
            c++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Ted*_*opp 5

你似乎有一个太多的嵌套循环.由于测试c <= input,你得到一个新的路线; 当input达到3时c >= 3,你执行换行并重置c为1.

我会写这样的循环:

for (int r = 1; input >= 0; ++r) {
    for (int c = 1; c <= r && input >= 0; ++c, --input) {
        System.out.print(input + " ");
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)