Susie Sharkie
Susie Sharkie

Reputation: 11

how to initialize Matrix object

I create a class called MATRIX which has one attribute

int [][] _matrix;

In another class I create an obj of type MATRIX:

Matrix newMatrix=new Matrix();

I want to initialize the obj like in this example:

int [][] a={{1,2,3}, {2,2,4}}

I try to write

newMatrix._matrix={{1,2,3}, {2,2,4}}

and I got a syntax error.

What did I've done wrong?

Upvotes: 1

Views: 1897

Answers (4)

rohit prakash
rohit prakash

Reputation: 575

This way you can initialize your matrix

class Matrix {
    int[][] _matrix;

    public int [][] get_matrix(){
        return this._matrix;
    }

    public void set_matrix(int [][] a){
        this._matrix = a;
    }
}


public class Test {
    public static void main(String [] args){
        Matrix matrix = new Matrix();
        matrix.set_matrix(new int[][]{{1,2,3}, {2,2,4}});
        System.out.print(matrix.get_matrix());
    }
}

OR you can create a static properties in class and then initialize with class name

Upvotes: 0

Akshay Bande
Akshay Bande

Reputation: 2587

newMatrix._matrix={{1,2,3}, {2,2,4}} is not allowed according to docs. I have added alternate way to achieve the same results.

package com.psl;

public class Test {

public static void main(String[] args) {

    Matrix matrix = new Matrix();

    matrix._matrix = new int[][]{{1,2,3}, {2,2,4}};


}

}

Upvotes: 0

TreffnonX
TreffnonX

Reputation: 2930

newMatrix._matrix = new int[][] {{1,2,3}, {2,2,4}};

The reason your code does not compile is because you are missing the new int[][] statement. It is required in a line, where you want to use a shortcut array initializer. See this question: How to initialize an array in Java?

Upvotes: 0

Chaitanya
Chaitanya

Reputation: 3638

Considering your basic example,

public class Matrix {

    int[][] _matrix;
}

You can initialize matrix as follows

public class Caller {

    public static void main(String[] args) {
        Matrix m = new Matrix();
        m._matrix = new int[][]{{1,2,3}, {2,2,4}};
    }
}

Upvotes: 5

Related Questions