Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix java.lang.arrayindexoutofboundsexception: 0?

Tags:

java

I'm a newbie to java. Can anyone pls help me with resolving the error arrayindexoutofboundsexception.

public class Minesweeper { 
   public static void main(String[] args) { 

      int M = Integer.parseInt(args[0]);
      int N = Integer.parseInt(args[1]);
      double p = Double.parseDouble(args[2]);

      // game grid is [1..M][1..N], border is used to handle boundary cases
      boolean[][] bombs = new boolean[M+2][N+2];
      for (int i = 1; i <= M; i++)
         for (int j = 1; j <= N; j++)
            bombs[i][j] = (Math.random() < p);

      // print game
      for (int i = 1; i <= M; i++) {
         for (int j = 1; j <= N; j++)
            if (bombs[i][j]) System.out.print("* ");
            else             System.out.print(". ");
         System.out.println();
      }

      // sol[i][j] = # bombs adjacent to cell (i, j)
      int[][] sol = new int[M+2][N+2];
      for (int i = 1; i <= M; i++)
         for (int j = 1; j <= N; j++)
            // (ii, jj) indexes neighboring cells
            for (int ii = i - 1; ii <= i + 1; ii++)
               for (int jj = j - 1; jj <= j + 1; jj++)
                  if (bombs[ii][jj]) sol[i][j]++;

      // print solution
      System.out.println();
      for (int i = 1; i <= M; i++) {
         for (int j = 1; j <= N; j++)
            if (bombs[i][j]) System.out.print("* ");
            else             System.out.print(sol[i][j] + " ");
         System.out.println();
      }

   }
}

and here is the exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Minesweeper.main(Minesweeper.java:5) 
like image 204
user26 Avatar asked Nov 29 '22 11:11

user26


2 Answers

Two things probably as it says index 0 (see first case for the same):

  1. You are not passing arguments to your main class.

  2. Array index always start from 0 and not 1. So you might need to change either:

    • your loop to start with 0 and check i < M or N
    • You use array index as i - 1 instead of i.

Reason you are getting ArrayIndexOutOfBoundException is lets say you have 2 elements in an array. It will be as below:

a[0] = 1;
a[1] = 2;

And when you are looping using i = 1; i<=2 you are accessing:

a[1] - which is perfect
a[2] - which was not expected?
like image 75
SMA Avatar answered Dec 11 '22 03:12

SMA


You have to check the length of the array args before accessing an element. Since you have to access 2nd element in the array, the lengh should be atleast 3. You have to check that like below

if(args.length > 2) {
  //wrap all code here
}
like image 36
Abimaran Kugathasan Avatar answered Dec 11 '22 04:12

Abimaran Kugathasan