How to initialize a complex instance variable in Java?

I am making a class called Matrix. Its instance variables should be the number of rows, the number of columns, and the 2D int array representing the matrix (in math). It has methods getDeterminant()that gets its determinant, and it should be able to reproduce with another matrix.

My question is in the constructor, how to initialize it? If it accepts a finished 2D array, so its constructor looks like this:

public class Matrix {
    private int[][] matrix;
    public Matrix(int[][] matrix) {
        this.matrix = matrix;
        //etc.
    }
}

or should he create it inside the constructor so that it looks like

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
}

EDIT: Or, should I have a method that initializes it as

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
}
+4
source share
2 answers

( int [] []), , .

(, setValue (int x, int y, int value).

, IO (.

. , . Matrix Matrix.

0

,

  • java - , .
  • : 1. 2.

Say

  • , .

  • , , , , , .

,

-1

Source: https://habr.com/ru/post/1655015/


All Articles