gpt4 book ai didi

java - 在 Java 中对模式使用循环的不同变体

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:26:06 25 4
gpt4 key购买 nike

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

图案

1
121
12321
1234321

我的代码如下,但与上面的示例不同。

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

最佳答案

您的代码仅打印每行的后缀,您缺少为每行编写 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
}

关于java - 在 Java 中对模式使用循环的不同变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29741163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com