我在做一個名爲Matrix的課。它的實例變量應該是它的行數,列數和一個代表矩陣的二維詮釋數組(在數學中)。它有方法getDeterminant()
它得到它的決定因素,它應該能夠與另一個矩陣相乘。我應該如何在Java中初始化一個複雜的實例變量?
我的問題是,在構造函數中,我應該如何初始化它?如果它接受一個預製的二維數組,這樣它的構造是這樣的:
public class Matrix {
private int[][] matrix;
public Matrix(int[][] matrix) {
this.matrix = matrix;
//etc.
}
}
,或者它應該在構造函數中創建它,使它看起來像
public class Matrix {
private int[][] matrix;
public Matrix(int rows, int columns) {
Scanner in = new Scanner(System.in);
//asks the user to input a matrix
}
//methods and the such
}
編輯: 或者,我應該有一個方法初始化它像
public class Matrix {
private int[][] matrix;
public Matrix() {
//something else
}
public int[][] initializeMatrix(int rows, int columns) {
//for loop + Scanner nextInt() to ask the user to input matrix
}
//methods and the such
}
我會更喜歡* * **的**第一選擇。 –
您可以根據選擇創建兩者。我不會把掃描儀的東西放在'int,int'構造函數中。做一個用例,然後管用戶輸入 – Li357
第一個選項不是很好,但肯定沒問題。第二個選擇是可怕的,不應該使用。 –