简体   繁体   English

java-如何使用两个2D数组计算2个数字的总和?

[英]java- how to calculate sum of 2 numbers using two 2D arrays?

I have to write a program which allows the input of two numbers in two 2*3 arrays and displays the sum of the corresponding numbers. 我必须编写一个程序,该程序允许在两个2 * 3数组中输入两个数字并显示相应数字的总和。 I am not able to understand why and how the program is to be implemented using two 2*3 arrays so basically I am at a lost of how it should actually be working. 我无法理解为什么以及如何使用两个 2 * 3数组来实现该程序,因此基本上我不知道它实际上应该如何工作。 But still here is what I have come up so far: 但是到目前为止,这仍然是我提出的内容:

package lesson1;
import java.util.*;

class MyClass{
public static void main(String[] args) {

    Scanner input= new Scanner(System.in);

    int sum;

    int array1[][]= new int[2][3];
    int array2[][]= new int[2][3];

    for(int i=0; i<array1.length; i++){

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

            array1[i][j]= input.nextInt();

            for(int x=0; x<array2.length;x++){
                for(int y=0; y<array2.length; y++){

                    array2[x][y]= input.nextInt();

                sum= array1[i][j]+ array2[x][y];
                System.out.println("The sum is "+sum);
                }

             }

            }


        }


         }           


    }

I believe that your code is too much complicated 我相信您的代码太复杂了

At first you have two arrays, the array1 and the array2. 首先,您有两个数组,分别为array1和array2。 That's fine but you don't need to create four " for "s, for that. 这很好,但你并不需要创建四个“ ” S,对于。

You can do 你可以做

for (int i = 0; i < array1.length; i++) {
     for (int y = 0; y < array1[i].length; y++ {
         array1[i][y]= input.nextInt();
         array2[i][y]= input.nextInt();
         sum = sum + array1[i][y] + array2[i][y];
     }
}

to fill them up and sum them. 填补他们并总结它们。

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

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