java 使用 * 星打印 Z 形金字塔
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33172657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print a Z shape pyramid using * stars
提问by Kyle
I am trying to write a program that outputs a Z pattern that is n
number of *
across the top, bottom, and connecting line using for loops.
我试图写一个程序,其输出是Z模式n
的数量*
在顶部,底部,并使用循环连接线。
Example:
例子:
Enter a number: 6
******
*
*
*
*
******
This is my current code, it's producing a half pyramid upside down.
这是我当前的代码,它产生了一个倒置的半金字塔。
import java.util.*;
public class ZShape {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = n; y >= 1; y--) {
if (y > x) {
System.out.print("* ");
}
else
System.out.print(" ");
}
System.out.println();
}
}
}
回答by Tunaki
This is the logic in the following code:
这是以下代码中的逻辑:
- Loop over each row of the output (so from 0 to
n
excluded so that we haven
rows) - Loop over each column of the output (so from 0 to
n
excluded so that we haven
columns) - We need to print a
*
only when it is the first row (x == 0
) or the last row (x == n - 1
) or the column is in the opposite diagonal (column == n - 1 - row
)
- 循环输出的每一行(所以从 0 到
n
排除,以便我们有n
行) - 循环输出的每一列(所以从 0 到
n
排除,以便我们有n
列) *
只有在第一行 (x == 0
) 或最后一行 (x == n - 1
) 或该列位于对角线 (column == n - 1 - row
)时才需要打印 a
Code:
代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
if (row == 0 || row == n - 1 || column == n - 1 - row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Sample output for n = 6
:
示例输出n = 6
:
******
*
*
*
*
******
(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).
(请注意,此输出的每一行都有尾随空格,您没有指定是否应包含它们,但通过添加另一个检查很容易删除它们)。
回答by Ryan
How about using three loops instead?
改用三个循环怎么样?
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println();
for (int x = n-3; x >= 0; x--) {
for (int y = x; y >= 0; y--) {
System.out.print(" ");
}
System.out.println("*");
}
for (int x = 0; x < n; x++) {
System.out.print("*");
}
回答by Sw?sh S?t?ka?t
public class Star {
public static void main(String[] args) {
for (int i = 0; i <=4; i++) {
for (int j = 0; j <=4; j++)
{
if (i==4 || (i+j)==4 || i==0)
{
System.out.print(" * ");
}
else
{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}