Lig*_*cab 1 java algorithm loops for-loop
我一直在尝试使用java中的for循环语句打印不同的模式.现在我想学习如何打印以下模式.它基本上是一种倾斜的金字塔型图案.
*
**
***
****
***
**
*
Run Code Online (Sandbox Code Playgroud)
我试图制作它并且我确实得到了正确的结果,但问题是我认为我这样做是一种不方便的方法.这是代码:
for (int x = 1; x <= 4; x++) {
for (int y = 1; y <= x; y++) {
System.out.print("*");
}
System.out.println();
}
for (int x = 1; x <= 3; x++) {
for (int y = 3; y >= x; y--) {
System.out.print("*");
}
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
你的代码产生了正确的输出,它对我来说足够清晰.我可以做的唯一建议是使用变量作为金字塔的大小而不是硬编码值.
你可以用更紧凑的方式编写它,只使用2个循环,如下所示:
int size = 7;
for (int row = 0; row < size; row++) {
for (int column = 0; column <= Math.min(size-1-row, row); column++) {
System.out.print("*");
}
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
这里的想法是:
size排除)size-1-row(随行增加而减少).所以星号的数量是最小的row和size-1-row:这是在单个语句中使用的因素Math.min(size-1-row, row).