What is the correct way to make a constructor’s argument accessible to different methods within a class?
For example, in the code snippet below, I want to make N accessible within a method called aMethod, without changing aMethod’s existing argument signature. Is myArray.length the best alternative?
public class MyClass{
private int[][] myArray;
public MyClass(int N){
if(N <= 0)
throw new IndexOutOfBoundsException("Input Error: N <= 0");
myArray = new int[N][N];
}
public void aMethod(int i, int j){
// N won't work here. Is myArray.length the best alternative?
if(i <= 1 || i > N)
throw new IndexOutOfBoundsException("Row index i out of bounds");
if(j <= 1 || j > N)
throw new IndexOutOfBoundsException("Column index j out of bounds");
}
}
EDIT 1
I’m testing for inputs greater than 0 so if a user enters 0 for i or 0 for j, the input is invalid.
Just create a field for it, like you did for the array.
However in this case I wouldn’t do that, I’d change aMethod() instead:
(I also changed the check to allow [0..N-1] instead of [1..N], as arrays are indexed from 0.)