Sandy.Arv
Sandy.Arv

Reputation: 605

2d array size based on input

I have a code where in, an array is to be defined, in which the size is based on user input. How do I do that?

My code is as follows:

public static void main(String args[]) throws Exception {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter the number of layers in the network:");
    int Nb_Layers = in.nextInt();
    int[] Hidden_layer_len = new int[Nb_Layers];


    for (int i = 0; i < Nb_Layers-1; i++)
    {
        System.out.println("Enter the length of layer" +(i+1)+":");
        Hidden_layer_len[i] = in.nextInt();

        if(i == 0)
        {
            double [][] E = new double[Hidden_layer_len[i]][1];//This is the array I need based on the size mentioned.

        }
    }

    System.out.println(E);
}

I want this to be a 2D array. Any suggestions would be appreciated. thank you!

Upvotes: 1

Views: 134

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

You can define the array outside the for loop and assign inside. E.g.

double[][] E = null;
for (int i = 0; i < Nb_Layers - 1; i++) {
    System.out.println("Enter the length of layer" + (i + 1) + ":");
    Hidden_layer_len[i] = in.nextInt();

    if (i == 0) {
        E = new double[Hidden_layer_len[i]][1];
    }
}

This way it will be available when you print it at the end.
By the way you probably want to print it like this

System.out.println(Arrays.deepToString(E));

Upvotes: 1

Related Questions