Java編寫三角形和平行四邊形

三角形 

public class 正三角 {
    public static void main(String[] args) {
        for (int j = 1; j <= 4; j++) {
            for (int i = 4; i>=j; i--) {
                System.out.print(" ");
            }
            for(int a = 1;a<=j;a++){
                System.out.print("*");
            }
            for(int b = 1;b<j;b++){
                System.out.print("*");

            }
            System.out.println();
        }
    }
}

咱們能夠看一下最終效果java

加載中

幾個簡單的for循環組成了這個正三角,咱們能夠把這個三角形劃分一下,這樣更方便咱們理解for循環的構成。spa

 

把這樣一個圖形分爲三部分,首先進行第一個for循環code

for (int j = 1; j <= 4; j++)

輸入第一行,即j=1時;for循環

for (int i = 4; i>=j; i--) {
    System.out.print(" ");
}

此時這個for循環(用於輸出第一個部分)要進行5次,第5次i<j,因此輸出4個空格後跳出循環;class

for(int a = 1;a<=j;a++){
    System.out.print("*");
}

此時這個for循環(用於輸出第二個部分)要進行2次,第2次a>j,因此輸出一個 * 後跳出循環;循環

for(int b = 1;b<j;b++){
    System.out.print("*");
}

此時這個for循環(用於輸出第三個部分)要進行1次,但b=j,因此第一次循環中斷,什麼都不輸出,這樣第一輪循環就進行完了,接着進行第二輪循環,即j=2時..........im

平行四邊形

public class 平行四邊形 {
    public static void main(String[] args) {
        for (int j = 1; j <= 4; j++) {
            for (int i = 1; i<j; i++) {
                System.out.print(" ");
            }
            for(int a = 4;a>=j;a--){
                System.out.print("*");
            }
            for(int b = 1;b<j;b++){
                System.out.print("*");

            }
            System.out.println();
        }
    }
}

最終效果:static

平行四邊形和三角形的思路相同,劃分爲三部分;img

剩下的for循環和三角形的循環相似,只有輸出順序不一樣。co

相關文章
相關標籤/搜索