简体   繁体   English

用Java添加两个矩阵

[英]Add two matrices in Java

I'm trying to add two matrices and I get and exception when the compiler attempts to call the sum method. 我正在尝试添加两个矩阵,当编译器尝试调用sum方法时,我得到了异常。

public static void main(String[] args) {

    int[][] a = new int[3][3];
    int[][] b = new int[3][3];

    for (int i = 0; i < a.length; i++)
    {
        for (int j = 0; j < a[0].length; j++)
        {
            a[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter a[" + i + "][" + j + "]"));
        }
    }
    for (int i = 0; i < b.length; i++)
    {
        for (int j = 0; j < b[0].length; j++)
        {
            b[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter b[" + i + "][" + j + "]"));
        }
    }

I get the exception at the next line. 我在下一行得到例外。

    int[][] c = sum(a,b);

    for (int[] row: c)
    {
        for (int e: row)
        {
            System.out.print(e + "\t");
        }
    }

}
public static int[][] sum(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; i < a[i].length; j++)
            c[i][j] = a[i][j] + b[i][j];
    }
    return c;
}

Anybody can help me with that? 有人可以帮我吗?

You have a typo in your inner loop: 您的内循环中有错别字:

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

should be 应该

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

and causes an ArrayIndexOutOfBoundsException since j goes beyond the size of the array. 并导致ArrayIndexOutOfBoundsException因为j超出了数组的大小。

When an exception occurs, the first thing you look at is the name of the exception. 发生异常时,您首先要查看的是异常的名称。 It's often very informative. 它通常非常有用。 In this case it tells us that we accidentally looped too far. 在这种情况下,它告诉我们我们不小心循环了太多。 If the name isn't informative, we can at least find out where the error occurred. 如果名称不完整,我们至少可以找出错误发生的地方。 The stack trace contains the line at which the error occurred. 堆栈跟踪包含发生错误的行。 If none of those things helps/exists, we can use a debugger, or print debug messages along the way, to diagnose the problem. 如果所有这些都不帮助/存在,我们可以使用调试器,或一路打印调试消息来诊断问题。

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

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