简体   繁体   English

在java中将数字打印为三角形

[英]printing numbers as a triangle in java

In this problem the user has to input the starting number and the size of the triangle.if starting number is 5 and size of the triangle is 6 the output must be like this.在这个问题中,用户必须输入起始编号和三角形的大小。如果起始编号为 5,三角形的大小为 6,则输出必须是这样的。

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

I have already tried this problem and their is a error with my code.我已经尝试过这个问题,他们是我的代码错误。 Can someone help me to find the error with this.有人可以帮我找到这个错误。

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

You forgot a你忘记了一个

cend--;

Put it there:把它放在那里:

    sizer-=2;
    cend--;
}

I would also recommend that you change your variable names into words so that it is possible for other people to read your code.我还建议您将变量名称更改为单词,以便其他人可以阅读您的代码。 For example, cend could be "columnEnd".例如,cend 可以是“columnEnd”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM