简体   繁体   中英

Index out of bounds exception in Java

This is a pretty simple method to check the bounds of an element in a grid. It is giving me an exception for a reason I cannot figure out.

Here is the method-

 Public class Percolation
{
 public int N;
 private boolean[][] grid;

 public Percolation(int N)               //  
  {
   checkNegative(N);
   grid = new boolean[N][N];
   }

 public void checkBounds(int i, int j)  
 {
     if(( i > N )||( j > N))
         {
          throw new java.lang.IndexOutOfBoundsException("Index out of bounds- " + i + "," + j + " out of bounds");
         }
     else
       return;
 }


 public void checkNegative(int N)
 {
   if( N <= 0)
       throw new java.lang.IllegalArgumentException("Number of sites less than 1");
 }

 public Percolation(int N)               
 {

   checkNegative(N);
   grid = new boolean[N][N];
 }  


 public void open(int i, int j)          
 {

   checkBounds(i,j);

   if (isOpen(i,j) == true)
       return;
   else
       grid[i][j] = true;
 }


 public boolean isOpen(int i, int j)     // is site (row i, column j) open?
{
   checkBounds(i,j);

   return grid[i][j];
}

public boolean isFull(int i, int j)     
 {
   checkBounds(i,j);

   return grid[i][j];
 }

 public boolean percolates()             // does the system percolate?
 {
   return false;
 }
 public static void main(String[] args)   // test client (optional)
 {
   int N;
   System.out.println("Enter grid length");
   Scanner in = new Scanner(System.in);
   N = in.nextInt();

   Percolation Perc = new Percolation(N);


   System.out.println("N is " + N);
   System.out.println(Perc.isOpen(2,3));
 }
}

The exception message I get along with the output is-

N is 10

java.lang.IndexOutOfBoundsException: Index out of bounds- 2,3 out of bounds

Your checkBounds method refers to an N that is not initialized, which means it remains 0 by default.

The only N in your code that gets initialized is local to the main method. It is passed to the Percolation constructor, but the constructor doesn't store it anywhere.

 public Percolation(int N)               
 {
   checkNegative(N);
   grid = new boolean[N][N];
   this.N = N; // this should fix it
 } 

变量N未初始化,其默认值为0,这就是为什么要获取此异常的原因。

There seems to be some missing code here for this example to make any sense. If I assume that you have renamed isOpen( , ) to checkBounds( , ), then I would suggest that you verify the N instance variable initialization. (may I suggest debugger)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM