So I'm currently supposed to write a method that takes a 2D Array as input and return a 1D Array. The problem is that I have trouble inputting a 2D Array to even test what I want to do.
That is the method.
public static int[] flatten (int[][] input)
flatten(null);
When I try to insert an example this is what it is supposed to look like: flatten([[1,2,3],[4,5,6]])
But then I get the error that "the left hand of an assignment must be a variable"?
CodePudding user response:
To pass a 2D Array as the input you should write it like this
int[][] input = {{1, 2, 3}, {4, 5, 6}};
int[] output = flatten(input);
or
int[] output = flatten(new int[][] {{1, 2, 3}, {4, 5, 6}} );
CodePudding user response:
This is how you would go about giving an argument to that method.
flatten(new int[][] { { 1, 2, 3 }, { 1, 2, 3 } });
In Java 1D array definitions can be expressed without the need to use the new int[]{...}
syntax, although it is still possible.
int[] someArray = { 1, 2, 3 }; // Perfectly valid
int[] someArray = new int[]{ 1, 2, 3 }; // Equally valid
However, 2D array definitions need to be explicitly stated when given as arguments to methods, in this way.
int[][] someArray = { { 1, 2, 3 }, { 1, 2, 3 } }; // Valid
flatten(someArray); // Valid
flatten(new int[][]{ { 1, 2, 3 }, { 1, 2, 3 } }); // Valid
flatten({ { 1, 2, 3 }, { 1, 2, 3 } }) // Invalid!