在Java中使用星号制作沙漏 [英] Making an hourglass using asterisks in java
问题描述
我知道有人问过这个问题,但是我很难理解其他程序和嵌套循环,如果有人有技巧遵循嵌套循环并用星号制作形状,我想知道,因为这确实让我感到困惑.
I know it's been asked but I'm having some hard time understanding other programs and nested loops, if someone has a trick to follow nested loops and making a shape with asterisks I would like to know because it really got me confused.
这是经过许多尝试和实验后我编写的代码:
Here is the code I wrote after many many tries and experiments:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int userentry = input.nextInt();
for (int i = 0; i < userentry - 1; i++) {
for (int k = 0; k < i; k++) {
System.out.print(" ");
}
for (int j = userentry - 1; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}
for (int i = 0; i < userentry; i++) {
for (int k = 0; k < i + 1; k++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
例如,数字条目3的输出是这样的,我在间距方面遇到了麻烦:
The output for the number entry 3 for example goes like this, i'm having trouble with the spacing:
***
**
*
**
***
我真的很感谢能为我的程序提供帮助并向我解释算法以及如何制作更多模式的人.
I would really appreciate someone who can help me with my program and explain me the algorithm and how can I make more patterns.
推荐答案
您可以将沙漏可视化为范围为 [-n,n]
的数字矩阵包含在内,其中每个点都是:
You can visualize a hourglass as a matrix of numbers in a range [-n, n]
inclusive, where each point is:
m[i][j] = Math.abs(i) - Math.abs(j);
如果 n = 3
,则此矩阵如下所示:
If n = 3
, then this matrix looks like this:
0 1 2 3 2 1 0
-1 0 1 2 1 0 -1
-2 -1 0 1 0 -1 -2
-3 -2 -1 0 -1 -2 -3
-2 -1 0 1 0 -1 -2
-1 0 1 2 1 0 -1
0 1 2 3 2 1 0
int n = 3;
IntStream.rangeClosed(-n, n)
.map(Math::abs)
.peek(i -> IntStream.rangeClosed(-n, n)
.map(Math::abs)
.mapToObj(j -> i < j ? " " : "* ")
.forEach(System.out::print))
.forEach(i -> System.out.println());
输出:
* * * * * * *
* * * * *
* * *
*
* * *
* * * * *
* * * * * * *
另请参见:
这篇关于在Java中使用星号制作沙漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!