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