クラス内のさまざまなメソッドがコンストラクターの引数にアクセスできるようにする正しい方法は何ですか?
たとえば、以下のコードスニペットでは、aMethodの既存の引数シグネチャを変更せずに、aMethodというメソッド内でNにアクセスできるようにします。myArray.lengthは最良の代替手段ですか?
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");
}
}
編集1 私は0より大きい入力をテストしているので、ユーザーがiに0を入力するか、jに0を入力すると、入力は無効になります。