我正在尝试编写一个程序,该程序输出一个 Z 模式,该模式是使用 for 循环n
顶部、底部和连接线的*
数。
例:
Enter a number: 6
******
*
*
*
*
******
这是我当前的代码,它正在颠倒产生半金字塔。
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();
}
}
}
这是以下代码中的逻辑:
- 遍历输出的每一行(因此从 0 到
n
排除,以便我们有n
行( - 遍历输出的每一列(因此从 0 到
n
排除,以便我们有n
列( - 只有当
*
是第一行(x == 0
(或最后一行(x == n - 1
(或列在相反的对角线(column == n - 1 - row
(时,我们才需要打印
法典:
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();
}
}
n = 6
的示例输出:
******
*
*
*
*
******
(请注意,此输出的每一行都有尾随空格,您没有指定是否应包含它们,但通过添加另一个检查很容易删除它们(。
改用三个循环怎么样?
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(" ");
}
}
}
下面是打印 Z 形状的逻辑:
i = 1
时,则第一行将仅打印"#">- 当
i = n
时,最后一行将仅以相同的方式通过"#"打印 - 当
i = j
时,这意味着它将仅执行"#"的对角线
法典:
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();
}
}
public class Main
{
public static void main(String[] args) {
int i, j,n=5;
for(i = 1; i <= n; i++){
for(j = 1; j <= n ; j++){
if(i==1 || i+j == n+1 || i==n)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}