[英]Print a Z shape pyramid using * stars
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.我正在尝试编写一个程序,该程序使用 for 循环在顶部、底部和连接线上输出
n
个*
的 Z 模式。
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();
}
}
}
This is the logic in the following code:这是以下代码中的逻辑:
n
excluded so that we have n
rows)n
排除,以便我们有n
行)n
excluded so that we have n
columns)n
排除,以便我们有n
列)*
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
)x == 0
)或最后一行( x == n - 1
)或该列在对角线上( column == n - 1 - row
)时,我们才需要打印*
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). (请注意,此输出的每一行都有尾随空格,您没有指定是否应包含它们,但通过添加另一个检查很容易删除它们)。
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("*");
}
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(" ");
}
}
}
Here is a logic to print Z shape:这是打印 Z 形状的逻辑:
i = 1
, then the First line will print only "#"i = 1
,第一行将只打印“#”i = n
, then the Last line will print in same way by "#" onlyi = n
,最后一行将以相同的方式仅通过“#”打印i = j
, that means it will execute one diagonal line by "#" onlyi = j
,这意味着它将仅通过“#”执行一条对角线Code:代码:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
for (int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--) {
if (i == 1 || i == n || i == j) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.