【发布时间】:2015-06-03 00:35:42
【问题描述】:
这是这里的第一篇文章,如果我的问题不符合这里要求的标准,请原谅我。
我编写了一段代码,它从两个单独的文件中获取两个矩阵的输入,然后执行乘法并将数据输出到一个新文件中。
它为 2x3 或 3x3 矩阵提供了完美的输出。如果我输入 4x4 矩阵,我会得到数组索引超出运行时异常。我不明白原因,因为我动态创建索引
我在第 40 行得到一个数组索引越界异常。
我得到一个错误。
![片段][2]
-
列表项
public class MM { private BufferedReader br; private int sum = 0; private final static String matrixA="matrixA.txt"; private final static String matrixB="matrixB.txt"; public static void main(String[] args) { new MM().MathMultiplicationValues(matrixA, matrixB); } private void MathMultiplicationValues(String mat1, String mat2) { try { br = new BufferedReader(new FileReader(mat1)); String line; int mat1rows = 0, mat1cols = 0, mat2rows = 0, mat2cols = 0; while ((line = br.readLine()) != null) { mat1cols = line.split(" ").length + 1; mat1rows++; } br.close(); // To close file br = new BufferedReader(new FileReader(mat2)); // to read input from file. while ((line = br.readLine()) != null) { mat2cols = line.split(" ").length + 1; mat2rows++; } int[][] mat1vals = new int[mat1rows ][mat1cols ]; int[][] mat2vals = new int[mat2rows ][mat2cols ]; br.close(); br = new BufferedReader(new FileReader(mat1)); for (int i = 1; i < mat1rows + 1; i++) { line = br.readLine(); String[] colvals = line.split(" "); for (int j = 1; j < mat1cols; j++) { mat1vals[i][j] = Integer.parseInt(colvals[j - 1]); } } br.close(); br = new BufferedReader(new FileReader(mat2)); for (int i = 1; i < mat2rows + 1; i++) { line = br.readLine(); String[] colvals = line.split(" "); for (int j = 1; j < mat2cols; j++) { mat2vals[i][j] = Integer.parseInt(colvals[j - 1]); } } br.close(); if ((mat1cols-1) == mat2rows) { int[][] resltmat = new int[mat1rows + 1][mat2cols + 1]; for (int i = 1; i < mat1rows + 1; i++) { //Loop does matrix multiplication. for (int j = 1; j < mat1cols; j++) { for (int k = 0; k < mat2rows + 1; k++) sum = sum + mat1vals[i][k] * mat2vals[k][j]; resltmat[i][j] = sum; sum = 0; } } final PrintWriter pw = new PrintWriter("Answer.txt"); //Creates a new file called Matrix Answer. for (int i = 1; i < mat1rows + 1; i++) { for (int j = 1; j < mat2cols; j++) { pw.print(resltmat[i][j] + " "); // Writes the output to file the file called MatrixAnswer } pw.println(); } pw.close(); } else // If no of columns not equal to rows control passes to else block. System.out.println("Multiplication of Matrix is not possible because columns are not equal to rows"); } catch (Exception e) { e.printStackTrace(); } } }
【问题讨论】:
-
我没有给你的答案,但可能有帮助的是将(在我看来过长)方法(作为旁白也应该以低级驼峰命名)分成更小的例程.它不仅更具可读性,而且允许您编写更小的单元测试,帮助您查明错误的根源。
标签: java arrays matrix indexoutofboundsexception filereader