【问题标题】:Exception in thread main error in array program数组程序中的线程主错误异常
【发布时间】:2014-06-17 16:51:55
【问题描述】:
// 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

【问题讨论】:

  • 仔细查看 result 数组的大小
  • 在第一个示例中,arrayFirst2 x 3 矩阵,但 result2 x 2,因此失败。

标签: java exception exception-handling main


【解决方案1】:

第一个程序中的结果数组太小了。

【讨论】:

    【解决方案2】:

    更改关注

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

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

    另外,要了解有关 java 中数组的更多信息,请查看http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

    【讨论】:

    • @user3371292 如果给定的答案解决了您的问题,请将其标记为已接受的解决方案
    【解决方案3】:

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

    这里,arrayfirst 和 arraysecound 分别包含两行和三列(用逗号分隔的内花括号的数量表示行数,而写在这些内花括号内的数字表示列数) , 所以当你添加它们的元素并尝试存储结果时,你又需要一个两行三列的数组。

    所以,只需替换

    int 结果[][]= new int [2][2]; 和 int result[][]= new int [2][3];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多