使类中的不同方法可以访问构造函数的参数的正确方法是什么?
例如,在下面的代码片段中,我想让 N 在名为 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");
}
}
编辑 1 我正在测试大于 0 的输入,因此如果用户为 i 输入 0 或为 j 输入 0,则输入无效。
最佳答案
只需为其创建一个字段,就像为数组所做的那样。
public class MyClass{
private int[][] myArray;
private int myArraySize;
public MyClass(int N){
if(N <= 0)
throw new IndexOutOfBoundsException("Input Error: N <= 0");
myArray = new int[N][N];
myArraySize = N;
}
...
}
但是在这种情况下我不会这样做,我会改为更改 aMethod() :
public void aMethod(int i, int j){
// N won't work here. Is myArray.length the best alternative
if(i < 0 || i >= myArray.length )
throw new IndexOutOfBoundsException("Index i out of bounds");
if(j < 0 || j >= myArray[i].length)
throw new IndexOutOfBoundsException("Column index j out of bounds");
}
(我还更改了检查以允许 [0..N-1] 而不是 [1..N],因为数组从 0 开始索引。)
关于java - 构造函数的参数可以从另一个方法访问吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12072326/