【问题标题】:Display an ASCII diamond with nested for loops显示带有嵌套 for 循环的 ASCII 菱形
【发布时间】:2014-10-31 22:49:16
【问题描述】:

我正在尝试使用嵌套的 for 循环显示星号菱形。

到目前为止,这是我的代码:

public class Diamond {
    public static void main(String[] args) {
        int size = 9;
        for (int i = 1; i <= size; i += 2) {
            for (int k = size; k >= i; k -= 2) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop

        for (int i = 1; i <= size; i += 2) {
            for (int k = 1; k <= i; k += 2) {
                System.out.print(" ");
            }
            for (int j = size; j >= i; j--) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop
    }
}

这很接近,但我将 9 个星号的行打印两次。

如何调整第二个 for 循环以在 7 个星号和 2 个空格处开始输出?

【问题讨论】:

    标签: java for-loop nested ascii-art


    【解决方案1】:

    在您的第一个 for 循环中删除 = 标记并仅使用 &lt; 例如

    for (int i = 1; i < size; i += 2)
    

    完整代码:

    int size = 9;
    
    for (int i = 1; i < size; i += 2) {
        for (int k = size; k >= i; k -= 2) {
            System.out.print(" ");
        }
        for (int j = 1; j <= i; j++) {
            System.out.print("*");
        }
        System.out.println();
    }// end loop
    
    for (int i = 1; i <= size; i += 2) {
        for (int k = 1; k <= i; k += 2) {
            System.out.print(" ");
        }
        for (int j = size; j >= i; j--) {
            System.out.print("*");
        }
        System.out.println();
    }// end loop
    

    输出:

         *
        ***
       *****
      *******
     *********
      *******
       *****
        ***
         *
    

    【讨论】:

      【解决方案2】:

      java-11

      通过使用作为 Java-11 的一部分引入的 String#repeat,您可以使用单循环来完成。

      public class Main {
          public static void main(String[] args) {
              int size = 9;
              int midRowNum = size / 2 + 1;
              for (int i = 1 - midRowNum; i < midRowNum; i++) {
                  System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((midRowNum - Math.abs(i)) * 2 - 1));
              }
          }
      }
      

      输出:

          *
         ***
        *****
       *******
      *********
       *******
        *****
         ***
          *
      

      通过将空格量增加一个字符,您还可以打印菱形的变体:

      public class Main {
          public static void main(String[] args) {
              int size = 9;
              int midRowNum = size / 2 + 1;
              for (int i = 1 - midRowNum; i < midRowNum; i++) {
                  System.out.println("  ".repeat(Math.abs(i)) + "* ".repeat((midRowNum - Math.abs(i)) * 2 - 1));
              }
          }
      }
      

      输出:

              * 
            * * * 
          * * * * * 
        * * * * * * * 
      * * * * * * * * * 
        * * * * * * * 
          * * * * * 
            * * * 
              * 
      

      【讨论】:

        【解决方案3】:

        您可以使用for 循环打印asterisks (mathematical operators) 的菱形:

        int m = 4;
        int n = 4;
        for (int i = -m; i <= m; i++) {
            for (int j = -n; j <= n; j++) {
                int val = Math.abs(i) + Math.abs(j);
                System.out.print(val > Math.max(m, n) ? " " : "∗");
                if (j < n) {
                    System.out.print(" ");
                } else {
                    System.out.println();
                }
            }
        }
        

        输出:

                ∗        
              ∗ ∗ ∗      
            ∗ ∗ ∗ ∗ ∗    
          ∗ ∗ ∗ ∗ ∗ ∗ ∗  
        ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗
          ∗ ∗ ∗ ∗ ∗ ∗ ∗  
            ∗ ∗ ∗ ∗ ∗    
              ∗ ∗ ∗      
                ∗        
        

        您可以使用IntStreams 创建一个带有星号 菱形的二维数组:

        int m = 4;
        int n = 4;
        String[][] arr = IntStream.rangeClosed(-m, m)
                .mapToObj(i -> IntStream.rangeClosed(-n, n)
                        .map(j -> Math.abs(i) + Math.abs(j))
                        .mapToObj(j -> j > Math.max(m, n) ? " " : "∗")
                        .toArray(String[]::new))
                .toArray(String[][]::new);
        
        // formatted output
        Arrays.stream(arr)
                .map(row -> Arrays.stream(row)
                        .collect(Collectors.joining(" ", "[ ", " ]")))
                .forEach(System.out::println);
        
        [         ∗         ]
        [       ∗ ∗ ∗       ]
        [     ∗ ∗ ∗ ∗ ∗     ]
        [   ∗ ∗ ∗ ∗ ∗ ∗ ∗   ]
        [ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ]
        [   ∗ ∗ ∗ ∗ ∗ ∗ ∗   ]
        [     ∗ ∗ ∗ ∗ ∗     ]
        [       ∗ ∗ ∗       ]
        [         ∗         ]
        

        另见:
        Empty diamond shape with numbers
        Filling a 2d array with numbers in a rhombus form

        【讨论】:

          【解决方案4】:

          试试这个代码。使用 Math.abs 会简单很多。

          import java.util.Scanner;
          
          public class MakeDiamond {
              public static void main(String[] args) {
                  Scanner sc = new Scanner(System.in);
                  while (true) {
                      System.out.println("Let's Creat Diamonds");
                      System.out.println("If number increases Diamonds gets bigger. " +
                              "Please input number lager than 1 : ");
          
                      int user_input = sc.nextInt(); //gets user's input
                      System.out.println("");
          
                      int x = user_input;
                      int front_space = -5;
                      for (int i = 0; i < 2 * user_input + 1; i++) {
                          for (int a = front_space; a < Math.abs(i - user_input); a++) {
                              System.out.print("    ");
                          }
          
                          if (i < user_input + 1) {
                              for (int b = 0; b < 2 * i + 1; b++) {
                                  System.out.print("*  ");
                              }
          
                          } else if (i > user_input) {
                              for (int c = 0; c < 2 * x - 1; c++) {
                                  System.out.print("*  ");
                              }
                              x--;
                          }
                          System.out.print('\n');
                      }
          
                      System.out.println("\nRun Again? 1 = Run,  2 = Exit : ");
          
                      int restart = sc.nextInt();
                      System.out.println("");
                      if (restart == 2) {
                          System.out.println("Exit the Program.");
                          System.exit(0);
                          sc.close();
                      }
                  }
              }
          }
          

          【讨论】:

            【解决方案5】:

            您可以使用两个嵌套的 for 循环和一个 if else 语句,如下所示:

            public static void main(String[] args) {
                int n = 5;
                for (int i = -n; i <= n; i++) {
                    for (int j = -n; j <= n; j++)
                        if (Math.abs(i) + Math.abs(j) <= n
                                // in chessboard order
                                && (i + j) % 2 != 0)
                            System.out.print("*");
                        else
                            System.out.print(" ");
                    System.out.println();
                }
            }
            

            输出:

                 *     
                * *    
               * * *   
              * * * *  
             * * * * * 
            * * * * * *
             * * * * * 
              * * * *  
               * * *   
                * *    
                 *     
            

            【讨论】:

              【解决方案6】:

              只是为了好玩...... :) 试试我的代码......

              public class Diamond {
                  static String sp(int n) {
                      String s = "";
                      for (int i = 0; i < n; i++)
                          s += " ";
                      return s;
                  }
              
                  static String st(int n) {
                      String s = "";
                      for (int i = 0; i < n; i++)
                          s += "*";
                      return s;
                  }
              
                  static int abs(int n) {
                      if (n < 0)
                          return -n;
                      else
                          return n;
                  }
              
                  public static void main(String[] args) {
                      int size = 9;
                      for (int i = 0; i < size; i++) {
                          System.out.println(sp(abs((size - 1) / 2 - i)) +
                                  st(abs(9 - 2 * ((i + 5) % (size)))) +
                                  sp(abs((size - 1) / 2 - i)));
                      }
                  }
              }
              

              输出:

                  *    
                 ***   
                *****  
               ******* 
              *********
               ******* 
                *****  
                 ***   
                  *    
              

              【讨论】:

                【解决方案7】:
                int n = 9;
                for (int i = 0; i < n; i++) {
                    for (int k = n - 1; k > i; k--) {
                        System.out.print(" ");
                    }
                    for (int j = 0; j < 2 * i + 1; j++) {
                        System.out.print("*");
                    }
                    System.out.println("");
                }
                for (int j = 0; j < n - 1; j++) {
                    for (int k = j; k >= 0; k--) {
                        System.out.print(" ");
                    }
                    for (int i = 2 * (n - j - 1) - 1; i > 0; i--) {
                        System.out.print("*");
                    }
                    System.out.println("");
                }
                

                输出:

                        *
                       ***
                      *****
                     *******
                    *********
                   ***********
                  *************
                 ***************
                *****************
                 ***************
                  *************
                   ***********
                    *********
                     *******
                      *****
                       ***
                        *
                

                【讨论】:

                  【解决方案8】:

                  试试这个代码:

                  我已经改变了第一个循环:

                  for (int i = 1; i <= size-1; i += 2) {
                  

                  int size = 9;
                  
                  for (int i = 1; i <= size - 1; i += 2) {
                      for (int k = size; k >= i; k -= 2) {
                          System.out.print(" ");
                      }
                      for (int j = 1; j <= i; j++) {
                          System.out.print("*");
                      }
                      System.out.println();
                  }// end loop
                  
                  for (int i = 1; i <= size; i += 2) {
                      for (int k = 1; k <= i; k += 2) {
                          System.out.print(" ");
                      }
                      for (int j = size; j >= i; j--) {
                          System.out.print("*");
                      }
                      System.out.println();
                  }// end loop
                  

                  【讨论】:

                    【解决方案9】:

                    另一个有趣的答案,尝试 JDK16 记录。这个菱形不是在一行中循环不同的索引,而是在简单的声明中使用Math.abs

                    public record Diamond(int midx, int midy, int size) implements Shape {
                        public int right() { return midx + size; }
                        public int top()   { return midy + size; }
                    
                        /** Check if shape is drawn at this x,y position */
                        public boolean intersects(int x, int y) {
                            return Math.abs(midx-x) + Math.abs(midy-y) <= size;
                        }
                    }
                    

                    为所有Shape 类和通用draw 添加接口以打印出任何相交形状的星号:

                    public interface Shape {
                        /** Check if shape is drawn at this x,y position */
                        boolean intersects(int x, int y);
                    
                        /** Max X position used by this shape */
                        int right();
                        /** Max Y position used by this shape */
                        int top();
                    
                        /** Draw a series of shapes */
                        public static void draw(Shape ... shapes) {
                            // Work out largest X, Y coordinates (and print the shape list):
                            int ymax = Arrays.stream(shapes).peek(System.out::println)
                                                            .mapToInt(Shape::top  ).max().getAsInt();
                            int xmax = Arrays.stream(shapes).mapToInt(Shape::right).max().getAsInt();
                            System.out.println();
                    
                            // Visit all X,Y and see what will be printed
                            for (int y = ymax ; y > 0; y--) {
                                for (int x = 1 ; x <= xmax; x++) {
                                    boolean hit = false;
                                    for (int i = 0; !hit && i < shapes.length; i++) {
                                        hit = shapes[i].intersects(x,y);
                                    }
                                    System.out.print(hit ? "*" : " ");
                                }
                                System.out.println();
                            }
                            System.out.println();
                        }
                    }
                    

                    ... 以及绘制任意数量形状的主要工具 - 很容易定义新的 ASCII 艺术Shape 类:

                    public static void main(String[] args) {
                        Shape.draw(new Diamond(10, 7, 5));
                        Shape.draw(new Diamond(10, 7, 3), new Diamond(17, 5, 3), new Diamond(22, 8, 1));
                    }
                    

                    打印出来:

                    Diamond[midx=10, midy=7, size=5]
                    
                             *     
                            ***    
                           *****   
                          *******  
                         ********* 
                        ***********
                         ********* 
                          *******  
                           *****   
                            ***    
                             *     
                                   
                    
                    Diamond[midx=8, midy=7, size=5]
                    Diamond[midx=17, midy=5, size=3]
                    Diamond[midx=22, midy=8, size=1]
                    
                           *               
                          ***              
                         *****             
                        *******          * 
                       *********    *   ***
                      ***********  ***   * 
                       *********  *****    
                        *******  *******   
                         *****    *****    
                          ***      ***     
                           *        *      
                                           
                    

                    另见:Draw two ASCII spruce trees of specific heights

                    【讨论】:

                      【解决方案10】:

                      此代码运行良好。只需要删除重复两次的额外行...

                      class Diamond {
                          public static void main(String[] args) {
                              int size = 9;
                              for (int i = 1; i <= size; i += 2) {
                                  for (int k = size; k >= i; k -= 2) {
                                      System.out.print(" ");
                                  }
                                  for (int j = 1; j <= i; j++) {
                                      System.out.print("*");
                                  }
                                  System.out.println();
                              }// end loop
                      
                              for (int i = 1; i <= size; i += 2) {
                                  for (int k = 1; k <= i + 2; k += 2) { // I made change here
                                      System.out.print(" ");
                                  }
                                  for (int j = size - 2; j >= i; j--) { // I made change here
                                      System.out.print("*");
                                  }
                                  System.out.println();
                              }// end loop
                          }
                      }
                      

                      输出:

                           *
                          ***
                         *****
                        *******
                       *********
                        *******
                         *****
                          ***
                           *
                            
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-08-21
                        • 1970-01-01
                        • 2020-12-30
                        • 1970-01-01
                        相关资源
                        最近更新 更多