什么是正确的方法来使一个类中的不同方法可以访问构造函数的参数?构造函数的参数可从另一种方法访问?
例如,在下面的代码片段,我要让ň一个名为amethod方法方法中访问,而无需改变amethod方法的现有说法签名。 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");
}
}
EDIT 1 我测试,用于输入大于0,所以如果用户对于i或0进入0对于j,输入无效更大。
将它存储在一个字段? – Vlad