fox.josh fox.josh - 18 days ago 5
Java Question

Storing array data to two dimensional array when array is passed by method

Need to store the incoming arrays as a single two dimensional array.

public class Question {

static int row = 5;
static int column = 3;
static int[][] processedArrayData;

public static void processArrays(int[] incoming) {
processedArrayData = new int[column][row];

/*
* Need to store each incoming array as
* a single two dimensional array
*/

// This attempt gives me invalid data See "Invalid Example Output 1"
for (int i = 0; i < column; i++) {
for (int j = 0; j < row; j++) {
processedArrayData[i][j] = incoming[i];
}
}
for (int[] arr : processedArrayData) {
System.out.println(Arrays.toString(arr));
}




}

public static void main(String[] args) {
int[] array1 = {7, 7, 1, 3, 3};
int[] array2 = {9, 7, 0, 3, 8};
int[] array3 = {6, 6, 1, 3, 2};

processArrays(array1);
processArrays(array2);
processArrays(array3);
}

}


Invalid Example Output 1

[7, 7, 7, 7, 7]
[7, 7, 7, 7, 7]
[1, 1, 1, 1, 1]
[9, 9, 9, 9, 9]
[7, 7, 7, 7, 7]
[0, 0, 0, 0, 0]
[6, 6, 6, 6, 6]
[6, 6, 6, 6, 6]
[1, 1, 1, 1, 1]


Every attempt I try to do so results in an error. I am assuming is it I am trying traditional methods of storing the array to the 2d array and all the array information is known and accessible before hand. When I try to do so, only calling in one array at a time, I can not get it to work.

Answer

You would need to create an instance of class Question or make the variables also static.

static int[][] processedArrayData = new int[3][];
static int idx = 0;

public static void processArrays(int[] incoming) {
    processedArrayData[ idx++ ] = incoming;
}
Comments