簡體   English   中英

如何復制二維數組並添加新行以在 Java 中存儲列的總和?

[英]How can I copy a 2D array and add a new row to store the sum of the columns in Java?

基本上我有一個函數,它接收一個二維數組,添加一個額外的行,然后計算列的總和,並將每個單獨列的結果存儲在之前創建的額外行中。 這是我的代碼:

public static int[][] sum(int[][] array) {
    int tempArray[][] = new int[array.length + 1][array[0].length];

    for (int column = 0; column < tempArray[0].length; column++) {
        int total = 0;
        for (int row = 0; row < tempArray.length; row++) {
            total += tempArray[row][column];
        }

        tempArray[tempArray.length][column] = total;

    }

    return tempArray;
}

因此,當我運行 for 循環來打印結果時,由於某種原因,我收到了一個 ArrayIndexOutOfBounds 錯誤,該錯誤是指該函數。 我認為我的邏輯是正確的,但我似乎無法讓它發揮作用。 對於更多上下文,數組的值由用戶輸入。 謝謝誰能解答!

您獲得 ArrayIndexOutOfBounds 是因為您訪問的索引多於以下行中的數組邊界:

tempArray[tempArray.length][column] = total;

將其替換為以下行將解決您的問題:

tempArray[tempArray.length - 1][column] = total;

但是,您的代碼仍然無法正常工作,因為您的求和邏輯存在錯誤。 您正在通過以下行計算總數。

total += tempArray[row][column];

但是您的 tempArray 除了零沒有任何值。 要解決此問題,請確保通過數組的值啟動 tempArray,如下所示:

int tempArray[][] = new int[array.length + 1][array[0].length];

for(int i = 0; i < array.length; i++) {
    for(int j = 0; j < array[0].length; j++) {
        tempArray[i][j] = array[i][j];
    }
}

希望這將解決您的問題。 快樂編碼!

您尚未初始化tempArray[][]

tempArray[tempArray.length][column] = total

將其更改為

tempArray[tempArray.length-1][column] = total

這將解決索引越界問題。

public static int[][] sum(int[][] array) {
    int tempArray[][] = new int[array.length + 1][array[0].length];

    for (int column = 0; column < array[0].length; column++) {
        int total = 0;
        for (int row = 0; row < array.length; row++) {
            tempArray[row][column] = array[row][column];
            total += array[row][column];
        }

        tempArray[tempArray.length-1][column] = total; // resolves the index out of bound issue

    }

    return tempArray;
}

如果行的長度不同,提到的解決方案將不起作用。 例如,如果輸入數組是

int[][] input = new int[][] { { 1, 2, 3 }, { 2, 3 } };

此解決方案消除了此類問題

public static int[][] sum(int[][] array) {
    int[][] tempArray = new int[array.length + 1][];

    int maxLength = 0;
    for (int i = 0; i < array.length; i++) {
        tempArray[i] = Arrays.copyOf(array[i], array[i].length);

        maxLength = Math.max(maxLength, array[i].length);
    }

    tempArray[tempArray.length - 1] = new int[maxLength];
    for (int i = 0; i < maxLength; i++ ) {
        int total = 0;
        for (int[] row : tempArray) {
            if (i <= row.length - 1) {
                total += row[i];
            }
        }
        tempArray[tempArray.length - 1][i] = total;
    }
    return tempArray;
}

和測試

public static void main(String[] args) {
    int[][] arr = new int[][] { { 1, 2, 3 }, { 2, 3 } };
    System.out.println(Arrays.deepToString(sum(arr))); 
    // Output
    // [[1, 2, 3], [2, 3], [3, 5, 3]]
}

暫無
暫無

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

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