Diamond with nested for loop in Java

前端 未结 7 698
暗喜
暗喜 2021-01-23 13:27

I am trying to display a diamond of asterisks using nested for loops.

Here is my code so far:

public          


        
7条回答
  •  误落风尘
    2021-01-23 14:11

    java-11

    By using String#repeat, introduced as part of Java-11, you can do it with a single loop.

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

    Output:

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

    By increasing the amount of space by one character, you can also print a variant of the diamond:

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

    Output:

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

提交回复
热议问题