簡體   English   中英

在Java中找到2D數組的尺寸

[英]Find the dimensions of a 2D array in java

我在Java中玩Arrays,並對此產生了疑問。 如何在Java中找到2D數組的尺寸? 例如,我從System.in獲取一個數組輸入,並將其通過另一個方法傳遞,如下所示:

Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
    for(int j=0; j < 6; j++){
                arr[i][j] = in.nextInt();
        }
}
findSize(arr);
/*
*
*Other code
*
*/
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}

數組的兩個維度均大於0。感謝幫助。

該方法:

findSize(int[] inputArr){
//I want to find the dimensions of the array here
}

作為參數獲取二維數組

因此,您應該這樣做:

findSize(int[][] inputArr){
     int heiht = inputArr.length;
     int width = inputArr[0].length;
}

我只需要像這樣訪問數組的第0個元素:

int size = inputArr[0].length;

這樣就可以了!

二維數組是數組的數組。 要獲取第二維的實際長度(對於第一維的每個數組條目,它可以不同):

int[] findSize(int[][] inputArr) {
    int[] size = new int[inputArr.length];

    for (int i = 0; i < inputArr.length; i++) {
        size[i] = inputArr[i].length;
    }

    return size;
}

要獲得2D陣列尺寸1:

int size_1 = inputArr.length;

要獲得2D陣列尺寸2:

int[] size_2 = findSize(inputArr);

暫無
暫無

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

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