Java中的索引越界异常
这是一种检查网格中元素边界的非常简单的方法。它给了我一个例外,原因我无法理解 这里是方法-Java中的索引越界异常,java,exception,Java,Exception,这是一种检查网格中元素边界的非常简单的方法。它给了我一个例外,原因我无法理解 这里是方法- Public class Percolation { public int N; private boolean[][] grid; public Percolation(int N) // { checkNegative(N); grid = new boolean[N][N]; } public void checkBounds(in
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));
}
}
我在输出中得到的异常消息是-
N是10
java.lang.IndexOutOfBoundsException:Index out-bounds-2,3 out-bounds您的checkBounds方法引用了一个未初始化的N,这意味着它在默认情况下保持为0
代码中唯一被初始化的N是main方法的本地值。它被传递给Percolation构造函数,但构造函数不会将其存储在任何地方
public Percolation(int N)
{
checkNegative(N);
grid = new boolean[N][N];
this.N = N; // this should fix it
}
变量N未初始化,默认值为0,这就是为什么会出现此异常。对于本例,这里似乎缺少一些有意义的代码。
如果我假设您已将isOpen重命名为checkBounds,那么我建议您验证N实例变量初始化。我可以建议调试器在哪里定义了isOpen方法???您没有在渗流构造函数中赋值N。我没有把它放进去,因为我认为它不相关。等一下,我来编辑这个。你有一个公共int N;在public Percolationint N中也有一个参数,我建议更改变量名称,这样就不会有重复的变量,并且可以确定您是哪一个using@NikhilPrabhu事实上是这样