-1

Please, can some body help me out here. I have an Arrays of integer in the code below, i am looking for a solution to prevent Array Index Out Of Bounds Exception error. I will be very grateful if anyone can help me.

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

        }
    }

Thanks

yole
  • 92,896
  • 20
  • 260
  • 197
Sky Rider
  • 1
  • 3

1 Answers1

0

A line number where the error occurs would help. Also, does the error tell you what the out-of-bounds value is?

At any rate, you should probably test that neither r - 1 nor c - 1 are less than zero.

You should also test that field[r][c] isn't larger than 9.

kshetline
  • 12,547
  • 4
  • 37
  • 73