簡體   English   中英

僅使用行數初始化二維數組

[英]Initializing a 2D array with only the number of rows

因此,如果您一開始只聲明行數,我對如何在 Java 中使用 2D 數組感到有些困惑。 例如:

int[][] x = new int[5][];

但是你會如何繼續填充這 5 行呢? 我認為您需要先聲明每一行的大小,但我想不出這樣做的方法。 如果我嘗試執行以下操作:

x[0][0] = 5;

編譯器告訴我x[0]為空。

希望得到一些幫助,提前致謝。

你試圖定義一個二維數組:首先你指定了行數,但你沒有指定列數及其必要的。

例如,我為第一行定義了 2 列並分配了值:

int[][] x = new int[5][];
x[0] = new int[2];
x[0][0] = 5;
System.out.println(x[0][0]);

為了更好地理解二維數組,您需要閱讀更多內容:

https://www.programiz.com/java-programming/multidimensional-array

二維數組的元素是一維數組。 如果你直接定義一個數組new int[5][4]那么每行的長度是4 ,否則它可能會有所不同。 當您創建一個行長未定義的二維數組時,它的每個元素(實際上是一維數組)尚未初始化並且為null 當您創建int[]維數組時,默認情況下它用零初始化。 如果您直接定義二維數組,則其行的元素將初始化為零。

二維數組的初始化

您可以在沒有行長度的情況下定義列長度:

int[][] arr = new int[5][];

arr[0] = new int[]{1, 2, 3};
arr[3] = new int[2];
arr[3][1] = 9;
arr[4] = new int[]{3, 3, 2, 1, 6, 7};
// output:
[1, 2, 3]
null
null
[0, 9]
[3, 3, 2, 1, 6, 7]

您可以定義列和行長度:

int[][] arr2 = new int[3][3];
arr2[0][0] = 1;
// output:
[1, 0, 0]
[0, 0, 0]
[0, 0, 0]

您可以在創建時定義 2d 數組的每個元素,可選擇保留行以供進一步操作:

int[][] arr3 = new int[][]{{1, 2, 3}, {4, 5}, {6}, null};
// output:
[1, 2, 3]
[4, 5]
[6]
null

您無法訪問x[0][0]因為x[0]行不存在任何列。 在使用之前,您需要初始化一行中的每一列:

x[0] = new int[5];
x[1] = new int[5];

或使用循環:

for (int i = 0; i < 5; i++) {
    x[i] = new int[5];
}

只需這樣做:

public class ClassName {
    public static void main(String[] args) {
        //Assignment of multi-dimensional array
        int[][] multiarray = new int[2][3];
        // assign value to row "0" and col "0" index
        multiarray[0][0] = 23;
        System.out.println("My Age is:" + multiarray[0][0]);
    }
}
int ROWS = 5;
int COLUMNS = 12;
int[][] x = new int[ROWS][];

將所有ROWS的值初始化為零:

IntStream.range(0, ROWS).forEach(i -> {
    x[i] = new int[COLUMNS];
});

如果您想初始化為不同的值,例如。 -1 :

IntStream.range(0, ROWS).forEach(i -> {
    x[i] = new int[COLUMNS];
    Arrays.fill(x[i], -1);
});

暫無
暫無

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

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