简体   繁体   English

给定两个2D数组,将它们添加到第三个2D数组中

[英]Given two 2D arrays, add them into a third 2D array

I am going through everything that I learned over the course of this quarter and re-studying the topics that I feel I didn't truly grasp. 我将学习本季度所学到的所有内容,然后重新研究自己觉得没有真正掌握的主题。 One of them was the concept of adding a third 2D array that stores the information for a previous 2D array. 其中之一是添加第三个2D数组的概念,该数组存储了先前2D数组的信息。

The specific statement of what I should know by the end of this quarter was: 我在本季度末应该知道的具体陈述是:

"Given two 2D arrays, add them into a third 2D array" “给出两个2D数组,将它们添加到第三个2D数组中”

Here are my attempts to do this: 这是我尝试执行的操作:

public static void main (String[] args){
int [] [] arrayOneTwoD= {{5,4,3,2,1},{1,2,3,4,5}};
        int [] [] arrayTwoTwoD={{9,8,7,6,5},{5,6,7,8,9}};
        int [][] thirdArray= new int [4][4];

thirdArray(arrayOneTwoD,arrayTwoTwoD,thirdArray);
}

public static void thirdArray (int [][] arrayOneTwoD, int [][] arrayTwoTwoD, int [] []thirdArray){

        for(int i = 0; i < 3; ++i) {
            for(int j = 0; j < 3; ++j) {
                thirdArray[i][j] = arrayOneTwoD[i][j] + arrayTwoTwoD[i][j]; 
            }
        }
    }

I searched this topic on stack overflow a number of times but nothing comes up for printing into a third 2D array only from one single 2D array into another. 我多次在堆栈溢出中搜索此主题,但仅从一个2D数组打印到另一个2D数组,却没有任何结果可打印到第三个2D数组。

What am I doing wrong? 我究竟做错了什么?

you should do something like this: 您应该执行以下操作:

public static void main (String[] args){
    int [][] arrayOneTwoD= {{5,4,3,2,1},{1,2,3,4,5}};
    int [][] arrayTwoTwoD={{9,8,7,6,5},{5,6,7,8,9}};
    int [][] thirdArray = thirdArray(arrayOneTwoD,arrayTwoTwoD);
}

public static int[][] thirdArray(int[][] arrayOneTwoD, int[][] arrayTwoTwoD){
    // assuming both arrays have the same dimensions
    int[][] thirdArray = new int[arrayOneTwoD.length][arrayOneTwoD[0].length];
    for(int i = 0; i < arrayOneTwoD.length; ++i) {
        for(int j = 0; j < arrayOneTwoD[0].length; ++j) {
            thirdArray[i][j] = arrayOneTwoD[i][j] + arrayTwoTwoD[i][j]; 
        }
    }
    return thirdArray;
}

You'll want to figure out the dimensions of the arrays you're adding instead of hard-coding a value when you initialize the 3rd 2D array. 您将需要弄清楚要添加的数组的尺寸,而不是在初始化第3个2D数组时对值进行硬编码。 You'll also need these dimensions when you iterate in your for loop. 在for循环中迭代时,您还将需要这些尺寸。 If the two 2D arrays you're adding are different dimensions, the answer becomes a little more complicated. 如果要添加的两个2D数组的尺寸不同,答案将变得更加复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM