Java矩阵点积ArrayIndexOutOfBoundsException

我在第66行出现错误c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];。我手工浏览了索引,只是无法弄清楚索引出了什么问题。非常感谢您的帮助。


package arrayproducts;

import javax.swing.JOptionPane;

public class ArrayProducts {

    public static void main(String[] args) {

        String output = "";

        int rowA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixA."));

        int colA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixA."));

        int rowB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixB."));

        int colB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixB."));

        if( colA != rowB){

            output += "Cannot perform matrix operation: Inner matrix dimensions must agree.";

            output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";

            output += "\nMatrixB has a dimension of "+ rowB + " x " + colB + ".";

            JOptionPane.showMessageDialog(null, output);

            return;


        } else {

            output += "\nDot Product Begin:";

            int [][] a = new int[rowA][colA];

            output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";

            int [][] b = new int[rowB][colB];

            output += "\nMatrixA has a dimension of "+ rowB + " x " + colB + ".";

            JOptionPane.showMessageDialog(null, output);

            int [][] c = new int[rowA][colB];

            ////

            // enter first matrix

            for(int i = 0; i < rowA; i++){

                for(int j = 0; j < colA; j++){

                    a[i][j] = Integer.parseInt(

                        JOptionPane.showInputDialog("\nEnter an integer for MatrixA, row " + (i+1) + " and column " + (j+1) + "."));

                }

            }


慕勒3428872
浏览 154回答 2
2回答

慕尼黑8549860

我猜你打算在下面的代码中使用索引i,j,k代替rowA,colB等。c[rowA][colB]&nbsp;=&nbsp;c[rowA][colB]&nbsp;+&nbsp;a[rowA][colA]*b[colA][colB];

慕村9548890

我将向您展示一个简单的示例。int[]&nbsp;a&nbsp;=&nbsp;new&nbsp;int[3];该平均值a只能有3个值。a[0],&nbsp;a[1]&nbsp;and&nbsp;a[2]如果尝试a[3],它将超出范围。所以。你有int&nbsp;[][]&nbsp;c&nbsp;=&nbsp;new&nbsp;int[rowA][colB];并尝试访问c[rowA][colB]超出范围的内容。在你的三个for循环,我想,你想使用i,j和k。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java