Explain creating a pyramid in Java

后端 未结 7 1312
独厮守ぢ
独厮守ぢ 2020-12-18 17:04

I am in a beginner java programming class and currently reviewing loops. If there is one thing I just do not understand, it\'s pyramids. I have researched the book exercis

7条回答
  •  时光取名叫无心
    2020-12-18 17:50

    public static void main(String[] args) {
    
        // levels in the pyramid
        int x = 5;
    
        for (int i = 1; i <= x; i++) {
            // for spacing
            for (int j = 1; j <= x - i; j++){                System.out.print("   ");            }           // left half of the pyramid             for (int k = i; k >= 1; k--){
                System.out.print((k >= 10) ? +k : "  " + k);
            }
            // corresponding right half of the pyramid
            for (int k = 2; k <= i; k++) {               System.out.print((k >= 10) ? +k : "  " + k);
            }
            // next line
            System.out.println();
        }
    }
    

    Credit: http://www.skilledmonster.com/2013/10/28/java-pyramid-example-pattern-11/

提交回复
热议问题