简体   繁体   English

2D阵列中3x3的总和

[英]Sum of 3x3 in 2D-Array

Write a program in java that read two 3 by 3 matrix and find out their sum and display result? 在java中编写一个程序,读取两个3乘3矩阵,找出它们的总和并显示结果?

i tried this but i got Runtime error 我试过这个,但我得到了运行时错误

Scanner r=new Scanner(System.in);
   int [][]array = null;
    int[][]array2 = null;
  int total=0;
  System.out.println("Enter matrix");
  for(int row=0;row<array.length;row++){
      for(int col=0;col<array[row].length;col++){
             array[row][col]=r.nextInt();

             array[row][col]=r.nextInt()

; ;

   System.out.print("   "+total +"  ");

      total=array[row][col]+array2[row][col];
        System.out.println("   ");

You are not allocating any memory for the array references, they are referencing nothing(null)... Try: 你没有为数组引用分配任何内存,它们没有引用任何内容(null)...尝试:

int[][] array = new int[3][3];
int[][] array2 = new int[3][3];

Also, you are missing a semi-colon in 9th line of your code.Also,in same line, I believe it should be array2 & not array. 此外,您在代码的第9行中缺少分号。同样,在同一行中,我认为它应该是array2而不是数组。

The first FOR-Loop demonstrates how to input values in the arrays. 第一个FOR-Loop演示了如何在数组中输入值。 This code will require that the user inputs the values of both arrays simultaneously. 此代码将要求用户同时输入两个数组的值。

The second FOR-Loop demonstrates how to sum the values of each array. 第二个FOR-Loop演示了如何对每个数组的值求和。 Later, both arrays are added together. 之后,两个阵列都加在一起。

    //Since you know the the array will be 3x3,
    //declare it!
    int[][] array1 = new int[3][3];
    int[][] array2 = new int[3][3];

    int array1Total = 0;
    int array2Total = 0;
    int endResult;

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

        for (int y = 0; y < array1[x].length; y++) {

            array1[x][y] = r.nextInt();
            array2[x][y] = r.nextInt();

        }
    }

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

        for (int y = 0; y < array1[x].length; y++) {

            array1Total += array1[x][y];
            array2Total += array2[x][y];

        }
    }

    endResult = array1Total + array2Total;

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

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