使用*星星打印Z形金字塔

时间:2015-10-16 14:14:37

标签: java

我正在尝试编写一个程序,使用for循环在顶部,底部和连接线上输出n*个Z模式。

示例:

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(); 
      }      
   }
}

4 个答案:

答案 0 :(得分:6)

这是以下代码中的逻辑:

  • 循环输出的每一行(从0到n排除,以便我们有n行)
  • 循环输出的每一列(从0到n排除,以便我们有n列)
  • 我们需要仅在第一行(*)或最后一行(x == 0)或列在相反的对角线({{1}时打印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

(请注意,此输出的每行都有尾随空格,您没有指定是否应该包含它们,但是通过添加另一个检查很容易删除它们。)

答案 1 :(得分:1)

如何使用三个循环呢?

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("*");
}

答案 2 :(得分:0)

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(" ");
        }
}
}

答案 3 :(得分:0)

以下是打印Z形的逻辑:

  1. i = 1时,第一行将仅打印“#”
  2. i = n时,最后一行将仅以“#”以相同的方式打印
  3. 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();
    }
}
相关问题