The array is filled with a snake in a circle.

An error occurs:

"Exception in thread" java.lang.ArrayIndexOutOfBoundsException: -1 at para13.main (para13.java:20) ".

Help me fix it, please. Code:

public class para13{ public static void main(String[] args) { int z = 6; int[][] a = new int[z][z]; int x = 0, y = -1, l = 1; boolean ch; for (int i = 1; i<z*z; ++i){ if ((y+1<z) && (a[x][y+1] == 0)){ y = y + 1; a[x][y] = i; } else{ if ((x+1<z) && (a[x+1][y] == 0)){ x = x + 1; a[x][y] = i; } else{ if ((y-1<z) && (a[x][y-1] == 0)){ y = y - 1; a[x][y] = i; } else { if ((x-1<z) && (a[x-1][y] == 0 )){ x = x - 1; a[x][y] = i; } } } } //System.out.print("x " + x + " "); //System.out.println("y " + y); //printMas(a); } printMas(a); } public static void printMas(int[][] b) { //вывод массива for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { System.out.print(b[i][j] + "\t"); } System.out.println(); } System.out.println(); } } 
  • You have some kind of convoluted array filling logic, and apparently either the logic is incorrect or you implemented it incorrectly. But without knowing this logic, it’s hard to say something. - Vartlok
  • Filled with a snake. - danilenkodanila
  • And line 20 is where will it be? - Eugene Krivenja
  • @EugeneKrivenja if ((y-1 <z) && (a [x] [y-1] == 0)). This is 3 if - danilenkodanila

2 answers 2

Somehow it should work (only the problematic piece of code is indicated)

  if ((y-1<z) && (y>0) && (a[x][y-1] == 0)){ y = y - 1; a[x][y] = i; } else { if ((x-1<z) && (x>0) && (a[x-1][y] == 0 )){ x = x - 1; a[x][y] = i; } } 

You forget to check for reaching the bottom of the array when decrementing the index.

  • Thanks for the help! - danilenkodanila

In one of if , you also have no lower limit on y , which decreases all the time by 1 (in fact, it may even go to a minus, but it will fall when y == 0 , because you refer to y-1 )

 if ((y-1<z) && (a[x][y-1] == 0)){ y = y - 1; a[x][y] = i; } 

And as prompted, and in the following if you have a similar problem, but already with x .

You still try to prodabzhit before asking :)
Then think for yourself, since for me the further solution of this problem seems unacceptable to you for the community.

  • In the next if the same trouble with x :) - Eugene Krivenja
  • Thanks for the help! - danilenkodanila
  • @EugeneKrivenja Yeah, and the truth is, I wasn’t even interested in watching anything further :) - StateItPrimitive