如何在Java中使用for循环在Java中打印倾斜的金字塔图案? [英] How to print an inclined pyramid pattern in java using for loop in java?
问题描述
我一直在尝试使用java中的for循环语句打印不同的模式。现在,我想学习如何打印以下图案。基本上是一种倾斜的金字塔类型的图案。
I have been trying to print different patterns using for loop statement in java. And now I want to learn how to print the following pattern. It is basically an inclined pyramid type of pattern.
*
**
***
****
***
**
*
我试图做到这一点,但确实得到了正确的结果,但是问题是我认为我做这件事的方式很不方便。以下是代码:
I tried to make it and I did get the right results but the problem is that I think that the way I did it is an inconvenient way of doing it. Here is the code:
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();
}
推荐答案
您的代码会产生正确的输出对我来说很清楚。我唯一能建议的是使用一个变量作为金字塔的大小,而不是硬编码的值。
Your code produces the right output and it clear enough to me. The only suggestion I could make is to use a variable for the size of the pyramid instead of a hard-coded value.
您可以用更紧凑的方式编写它,仅使用2个循环,例如:
You could write it in a more compact manner, only using 2 loops, like this:
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();
}
这里的想法是:
- 对于金字塔的每一行(因此该行从0变为
大小
) - 我们需要确定要打印多少个星号。如果我们位于金字塔的上半部分,则等于我们所在的行。如果我们位于金字塔的下半部分,它等于
size-1-row
(随着行的增加而减少)。因此,星号的计数是行
和size-1行
的最小值:这是在单个语句中考虑的使用Math.min(size-1-row,row)
。
- For each row of the pyramid (so the row goes from 0 to
size
excluded) - We need to determine how many asterisks to print. If we are in the upper-half of the pyramid, it is the equal to the row we're at. It we are in the lower-half of the pyramid, it is equal to
size-1-row
(decreasing with the row increasing). So the count of asterisk is the minimum ofrow
andsize-1-row
: this is factored in a single statement usingMath.min(size-1-row, row)
.
这篇关于如何在Java中使用for循环在Java中打印倾斜的金字塔图案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!