在java中使用循环到模式的不同变体

Kir*_*ode 2 java algorithm loops

我一直在尝试for循环的不同变体,并且不知道如何制作这些模式:

图案

1
121
12321
1234321
Run Code Online (Sandbox Code Playgroud)

我的代码如下,但不像上面的例子那样工作.

for (int i = 1 ; i <= rows ; i++) {
    for (int j = (rows + 1 - i) ; j  > 0 ; j-- ) {
        System.out.print(j);
    }   
    System.out.print("\n");
 }
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 6

您的代码仅打印每行的后缀,您缺少12....i为每行写入.
另外,循环应该从而i不是从rows-i+1.

for (int i = 1 ; i <= rows ; i++) {
    //add an inner loop that prints the numbers 12..i
    for (int j = 1 ; j  < i ; j++ ) {
        System.out.print(j);
    }       
    //change where j starts from
    for (int j = i ; j  > 0 ; j-- ) { 
        System.out.print(j);
    }   
    System.out.println(""); //to avoid inconsistency between different OS
 }
Run Code Online (Sandbox Code Playgroud)