簡體   English   中英

基於輸入的二維數組大小

[英]2d array size based on input

我有一個代碼,其中要定義一個數組,其中的大小基於用戶輸入。 我怎么做?

我的代碼如下:

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);
}

我希望這是一個二維數組。 任何建議,將不勝感激。 謝謝你!

您可以在 for 循環外部定義數組並在內部分配。 例如

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];
    }
}

這樣,當您最后打印它時,它將可用。
順便說一句,您可能想像這樣打印

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM