什麼是正確的方法來使一個類中的不同方法可以訪問構造函數的參數?構造函數的參數可從另一種方法訪問?
例如,在下面的代碼片段,我要讓ň一個名爲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