簡體   English   中英

在java中將數字打印為三角形

[英]printing numbers as a triangle in java

在這個問題中,用戶必須輸入起始編號和三角形的大小。如果起始編號為 5,三角形的大小為 6,則輸出必須是這樣的。

5
19 6
18 20 7
17 25 21 8 
16 24 23 22 9
15 14 13 12 11 10

我已經嘗試過這個問題,他們是我的代碼錯誤。 有人可以幫我找到這個錯誤。

public class MyClass {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        //first number
        int n=in.nextInt();
        //size of the triangle
        int k=in.nextInt();
        int [][]arr=new int[k][k];
        int sizec=k,sizer=k,rstart=0,cstart=0,rend=k-2,cend=k-2,p=0;
        while(sizer>1&&sizec>1){
            int g=cstart;
            for(int i=rstart;i<sizer;i++){
                arr[g][i]=n;
                n++;
                g++;

            }
            for(int i=rend;i>=rstart;i--){
                arr[cend+1][i]=n;
                n++;

            }
            for(int i=cend;i>cstart;i--){
                arr[i][rstart]=n;
                n++;

            }
            rstart++;
            cstart+=2;
            rend-=2;
            sizec-=2;
            sizer-=2;
        }
        for(int j=0;j<k;j++){
            for(int h=0;h<j+1;h++){
                System.out.print(arr[j][h]+" ");
            }
            System.out.println();
        }
    }
}

你忘記了一個

cend--;

把它放在那里:

    sizer-=2;
    cend--;
}

我還建議您將變量名稱更改為單詞,以便其他人可以閱讀您的代碼。 例如,cend 可以是“columnEnd”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM