You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java矩阵乘法代码报错求助:ArrayIndexOutOfBoundsException异常

解决矩阵乘法代码中的ArrayIndexOutOfBoundsException问题

错误原因分析

  • 结果矩阵维度倒置:矩阵乘法中,A(r行c列)× B(c行r1列)的结果应为r行r1列,但代码中错误定义为int[][] nc = new int[r1][r];,当r > r1时,循环遍历x到r-1会超出nc的行数范围,触发索引越界。
  • 合法性检查滞后:代码在完成矩阵乘法计算后才检查是否满足乘法条件,此时异常可能已经触发,检查失去意义。
  • 固定矩阵大小的隐患:提前创建1000×1000的矩阵,若实际文件中矩阵规模超过该值,会直接抛出越界异常。
  • 变量命名混淆:读取matrixB时用c1表示行数,r1表示列数,与matrixA的命名逻辑不一致,增加出错概率。

修正后的代码

import java.io.*;
import java.util.*;

public class MM {
    public static void main(String[] args) throws IOException {
        // 读取矩阵A
        List<int[]> matrixAList = new ArrayList<>();
        Scanner s1 = new Scanner(new BufferedReader(new FileReader("matrixA1.txt")));
        while (s1.hasNextLine()) {
            String[] str = s1.nextLine().trim().split(" ");
            int[] row = new int[str.length];
            for (int x = 0; x < str.length; x++) {
                row[x] = Integer.parseInt(str[x]);
            }
            matrixAList.add(row);
        }
        s1.close();
        int[][] matrixA = matrixAList.toArray(new int[0][]);
        int rowsA = matrixA.length;
        if (rowsA == 0) {
            System.out.println("矩阵A为空");
            return;
        }
        int colsA = matrixA[0].length;

        // 读取矩阵B
        List<int[]> matrixBList = new ArrayList<>();
        Scanner s2 = new Scanner(new BufferedReader(new FileReader("matrixB1.txt")));
        while (s2.hasNextLine()) {
            String[] str1 = s2.nextLine().trim().split(" ");
            int[] row = new int[str1.length];
            for (int x = 0; x < str1.length; x++) {
                row[x] = Integer.parseInt(str1[x]);
            }
            matrixBList.add(row);
        }
        s2.close();
        int[][] matrixB = matrixBList.toArray(new int[0][]);
        int rowsB = matrixB.length;
        if (rowsB == 0) {
            System.out.println("矩阵B为空");
            return;
        }
        int colsB = matrixB[0].length;

        // 检查矩阵乘法合法性
        if (colsA != rowsB) {
            System.out.println("无法执行矩阵乘法:矩阵A的列数不等于矩阵B的行数");
            return;
        }

        // 执行矩阵乘法
        int[][] resultMatrix = new int[rowsA][colsB];
        for (int x = 0; x < rowsA; x++) {
            for (int y = 0; y < colsB; y++) {
                int sum = 0;
                for (int z = 0; z < colsA; z++) {
                    sum += matrixA[x][z] * matrixB[z][y];
                }
                resultMatrix[x][y] = sum;
            }
        }

        // 写入结果到文件
        BufferedWriter bfw = new BufferedWriter(new FileWriter("matrixAnswer.txt"));
        for (int x = 0; x < rowsA; x++) {
            for (int y = 0; y < colsB; y++) {
                bfw.write(Integer.toString(resultMatrix[x][y]));
                if (y < colsB - 1) {
                    bfw.write(" ");
                }
            }
            if (x < rowsA - 1) {
                bfw.newLine();
            }
        }
        bfw.close();
    }
}

代码说明

  1. 动态创建矩阵:使用ArrayList存储每行数据,再转换为二维数组,避免固定大小导致的越界问题,适配任意规模的矩阵。
  2. 修正结果矩阵维度:根据矩阵乘法规则,结果矩阵定义为int[][] resultMatrix = new int[rowsA][colsB];,确保维度正确。
  3. 提前合法性检查:在读取完矩阵后立即检查列数和行数是否匹配,不满足条件直接终止程序。
  4. 统一变量命名:用rowsA/colsA、rowsB/colsB明确表示矩阵的行和列,避免命名混淆。
  5. 资源关闭:主动关闭Scanner资源,避免资源泄漏。

内容的提问来源于stack exchange,提问作者Rayman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:23:13