Reputation: 3
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
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
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