When using java programming to display a spiral square, a if conditional statement is used to change the direction of the square array. But the order of the logic or condition in the if conditional statement is different.
public class SpiralMatrix {
public static void main(String[] args) {
int matrix[][] = new int[4][4];
/*Spiral direction is clockwise, so x, y coordinate
corresponding increase 1, unchanged or minus 1.*/
int xd[] = {0,1,0,-1};
int yd[] = {1,0,-1,0};
/*d=0,1,2,3 represents the right, down, left, and upper
directions, respectively.*/
int d = 0;
/*Next_x,next_y represents the subscript of the next matrix
element, respectively*/
int x=0,y=0,next_x,next_y;
for(int i=0;i<16;i++) {
matrix[x][y] = i+1;
next_x = x+xd[d];
next_y = y+yd[d];
/*When the subscript of the next matrix element does
not exist or exceeds the boundary or the array
element has been assigned a value*/
if(next_x<0||next_y<0||next_y==4||next_x==4||matrix[next_x][next_y]!=0) {
/*change direction*/
d = (d+1)%4;
next_x = x+xd[d];
next_y = y+yd[d];
}
x = next_x;
y = next_y;
}
/*output spiral matrix*/
for(int a=0;a<4;a++) {
for(int b=0;b<4;b++) {
System.out.print(matrix[a][b]+"\t");
}
System.out.println();
}
}
The above code outputs a correct result:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
But if you change the order of the conditions in parentheses in the if statement, for example:
if (matrix[next _ x][next _ y]! = 0 | | next _ x <0 | | next _ y <0 | | next _ y = = 4 | | next _ x = = 4)
Then run the program,the result shows that:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at code.SpiralMatrix.main(SpiralMatrix.java:19)