数组索引超出界限异常:0

时间:2018-03-07 09:50:16

标签: java arrays

拜托,有些人可以帮助我。我在下面的代码中有一个整数数组,我正在寻找一个解决方案来防止数据索引超出边界异常错误。如果有人能帮助我,我将非常感激。

 public class testing {

    public static void main(String[] args){

        int[][] field={ {0,0,0,0,0,0,0,0,0,0},
                        {0,0,1,1,0,0,0,0,0,0},
                        {0,0,1,1,1,0,0,0,0,0},
                        {0,0,1,0,0,0,1,1,1,0},
                        {0,0,0,0,0,0,0,1,1,0},
                        {0,0,0,0,0,0,0,0,0,0},
                        {0,0,0,0,0,0,0,0,0,0},
                        {0,0,0,0,1,1,0,0,0,0},
                        {0,0,0,0,1,1,0,0,0,0},
                        {0,0,0,0,0,0,0,0,0,0}

        };
        int sheepNo=1;
        int sheepSize=0;
        int sheepArray[]={0,0,0,0,0,0,0,0,0,0}; 
        for (int r=0;r<10;r++){
            for (int c=0;c<10;c++){
                if (field[r][c]==1){
                    if(field[r][c-1]!=0){
                        field[r][c]=field[r][c-1];
                        sheepSize++;
                        sheepArray[field[r][c]]=sheepSize;
                    } 
                    else if(field[r-1][c-1]!=0){
                        field[r][c]=field[r-1][c-1]; 
                        sheepSize++;
                        sheepArray[field[r][c]]=sheepSize;
                    } 
                    else if(field[r-1][c]!=0){
                        field[r][c]=field[r-1][c];
                        sheepSize++;
                        sheepArray[field[r][c]]=sheepSize;
                    } 
                    else if(field[r-1][c+1]!=0){
                        field[r][c]=field[r-1][c+1];
                        sheepSize++;
                        sheepArray[field[r][c]]=sheepSize;
                    } 
                    else{
                        field[r][c]=sheepNo++;
                        sheepSize=1;
                        sheepArray[field[r][c]]=sheepSize;
                    }

                }
                System.out.print(":"+field[r][c]);


                }
                System.out.println();
            }//end of loop
        for(int i=0;i<10;i++){
            System.out.println("No "+i+"  :  "+ sheepArray[i]);
        }

        }
    }

由于

1 个答案:

答案 0 :(得分:0)

发生错误的行号会有所帮助。此外,错误是否告诉您超出范围的值是什么?

无论如何,您应该测试r - 1c - 1都不会小于零。

您还应该测试field[r][c]是否大于9。