简体   繁体   中英

Whats wrong with this array?

public class lab {
    public static void main (String args[]){
        double[][] g = {RandomArray(3)};
        printArray(g);
    }

    private static void printArray(double[][] g) {
        System.out.println(Arrays.deepToString(g));
    }

    public static double[][] RandomArray(int n) {

        double[] [] RandomArray = new double[n] [n];
        Random randomNumberCreator = new Random();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
            }
        }
        return RandomArray;
    }
}

I am not sure what is wrong with my RandomArray method, i want it to work for 2-dimensional arrays but i have clearly made a mistake as the line below is receiving an error and I am unsure as to why this is happening. If you could explain to me the error that I have made i would be grateful.

double[][] g = {RandomArray(3)};

remove the curly brace around the function Call of "RandomArray"

  public static void main (String args[]){
        double[][] g = RandomArray(3);
        printArray(g);
    }

    private static void printArray(double[][] g) {
        System.out.println(Arrays.deepToString(g));
    }

    public static double[][] RandomArray(int n) {

        double[] [] RandomArray = new double[n] [n];
        Random randomNumberCreator = new Random();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
            }
        }
        return RandomArray;
    }

You are initializing the array incorrectly.... you dont need the { } when calling the method RandomArray

just doing double[][] g = RandomArray(3); will do the job

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM