lbxzero
lbxzero

Reputation: 3

Supplying elements to a 2 dimensional array in Java, why not working?

I want to fill a 2 dimensional array in Java with a specific set of numbers.

My sample array set: {{7,-4},{8,-2},{9,-1}}

How can I load the array without doing this?

int[][] x = new int[3][2];
x[0][0] = 7;
x[0][1] = -4;
x[1][0] = 8;
x[1][1] = -2;
x[2][0] = 9;
x[2][1] = -1;

Further, I thought I could do this, but I get "error: illegal start of expression."

class Alpha {
    int[][] x;

    public Alpha () {
        x = new int[3][];
        x[0] = {7,-4};    <== line where error is located
    }
}

Upvotes: 0

Views: 85

Answers (2)

Reimeus
Reimeus

Reputation: 159844

As each element of the outer array effectively points to a 1D array, you could do:

x[0] = new int[] {7,-4};

Upvotes: 2

Ajay S
Ajay S

Reputation: 48602

Try this.

You can initialize the two dimensional array like this.

int x[][] = {
                {7, -4},
                {8, -2},
                {9, -1}
            };

OR

x[0] = new int[] {7,-4};
x[1] = new int[] {8,-2};
x[2] = new int[] {9,-1};

Upvotes: 5

Related Questions