Question

// getting exception in thread main error in  result[row][col]= arrayfirst [row][col] + arraysecound [row[col];

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

     int arrayfirst[] [] ={{1,2,3},{2,3,4}};
     int arraysecound[] [] ={{3,4,5},{6,7,8}};
     int result[][]= new int [2][2];

      for(int row =0; row<arrayfirst.length; row++)
      {

          for(int col =0; col<arrayfirst[row].length; col++)
          { 

          result[row][col]= arrayfirst [row][col] + arraysecound [row][col];
          }
      }



      for(int row =0; row<arrayfirst.length; row++) {
            for(int col =0; col<arrayfirst[row].length; col++) { 
                System.out.print(" "+result[row][col]);
            } 
            System.out.println();
      }
}
}

// BUT THESE SIMILAR PROGRAMS RUNS CORRECTLY WHY

public static void main(String args[])
{

    int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
    int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};
    int arrayC[][] = new int[4][4];

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

        //  System.out.print(arrayC[i][j] + "   ");

        } // end j for loop
    } // end i for loop

    for (int i = 0; i < arrayC.length; i++) {
        for (int x = 0; x < arrayC[i].length; x++) {
                System.out.print(arrayC[i][x] + "  | ");
        }
        System.out.println();
    }
} // end main
} // end class
Was it helpful?

Solution

int arrayfirst[] [] ={{1,2,3},{2,3,4}}; int arraysecound[] [] ={{3,4,5},{6,7,8}};

here, arrayfirst and arraysecound contain two rows and three columns each (The number of inner curly braces separated by Comma signify number of rows, and the numbers written within these inner curly braces signify number of columns), so when you add their elements and try to store the result, you again need an array that has two rows and three columns.

so, just replace

int result[][]= new int [2][2]; with int result[][]= new int [2][3];

OTHER TIPS

Your result array in the first program is too small.

Change following

int result[][]= new int [2][2];

to

int result[][]= new int [2][3];

Also, to learn more about arrays in java, have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top