boersencrack boersencrack - 2 months ago 8
Java Question

java: use 3d array from method in main method

I have a method which is filling two of the three dimensions of an array.

public static String[][] Method(){
double[][][] chromosom = new double [50][8][4];
for(int j = 0; j < 8; j++){

// generate random value ...

chromosom[0][j][0] = value*2;
chromosom[0][j][1] = value*3;
chromosom[0][j][2] = value*5;
chromosom[0][j][3] = value*9;
}
}


Now I want to use this array in my main to generate 50 of these arrays and to save them all in one array.

static double[][][] chromosom = new double [50][8][4];

public static void main(String[] args){
for(int i = 0; i < 50; i++){
Method();
for(int j = 0; j < 8; j++){
chromosom[i][j][0];
chromosom[i][j][1];
chromosom[i][j][2];
chromosom[i][j][3];
}
}
}


My problem is that I am not able to reach the chromosom array with its values from my main method.

Answer

Your code doesn't compile. Your Method should return a String[][]. Why create the 3-dimension double array if this method should only create a 2-dimension String array? How about this:

public static double[][] generateXY(){
    double[][] result = new double[8][4];
    for(int j = 0; j < 8; j++){

        // generate random value ...

        result[j][0] = value*2;
        result[j][1] = value*3;
        result[j][2] = value*5;
        result[j][3] = value*9;
    }
    return result;
}

And then in your main:

public static void main(String[] args){
    double[][][] xyz = new double[50][8][4];
    for(int i = 0; i < 50; i++){
        xyz[i] = generateXY();
    }
}

Methods and variables should be renamed, I don't know what exaclty you're doing with it.

Comments