添加矩阵Java [英] Adding matrices Java

查看:67
本文介绍了添加矩阵Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是写一小段代码来添加矩阵.到目前为止,我编写的方法是:

I'm just writing a short piece of code for adding matrices. So far the method I have written is:

public static int[][] matrixAdd(int[][] A, int[][] B)
{
   int[][]C = new int[A.length][A[0].length];

   for(int i =0; i < A.length; i++)
  {
  for(int j=0; j < A[i].length;j++)
  {
     C[i][j] = A[i][j] + B[i][j]; 
  }
}


return C;
}

此代码确实正确添加了矩阵,但是如果传递给此方法的矩阵为空,则会出现索引超出范围的异常.该错误显然与"C"的大小变大的行有关.我的逻辑怎么了?

This code does add matrices correctly, however I get an index out of bounds exception if the matrices passed to this method are empty. The error apparantly relates to the line in which the size of 'C' is delared. What is wrong with my logic?

推荐答案

如果矩阵为空,则该语句

If matrixes are empty, the statement

 int[][]C = new int[A.length][A[0].length];

将抛出OutOfBoundsException,因为矩阵A的位置0无效.

will throw an OutOfBoundsException because the position 0 of the matrix A is invalid.

进行两次检查:

 if ((A.length < 0) || (A[0].length < 0)) return B;
 if ((B.length < 0) || (B[0].length < 0)) return A;

这篇关于添加矩阵Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆