在java中乘以2d数组(矩阵)

时间:2013-04-11 02:01:07

标签: java arrays multidimensional-array matrix

我的目标是在两个数组相乘时打印出Matrix。这段代码我做错了什么?如何获取它以便打印出矩阵? (对不起,我不知道我应该提供哪些其他细节,除非我添加更多详细信息,否则我无法提交此帖子)。

public class Matrices {
static int mRows = 0;
static int mCol = 0;
static int nRows = 0;
static int nCol = 0;
 public static int[][] multiplyMatrices(int[][] m, int[][] n){
    mRows = m.length;
    mCol = m[0].length;
    nRows = n.length;
    nCol = n[0].length;
    if(canBeMultiplied(m,n) == false){
        throw new IllegalArgumentException("Cannot multiply arrays");
    }
    int[][] answer = new int[mRows][nCol];
    for(int i = 0; i < mRows; i++){
        for(int j = 0; j < nCol; j++){
            for(int k = 0; k < mCol; k++){
                answer[i][j] += m[i][k] * n[k][j];
            }
        }
    }
    return answer;
}

public static boolean canBeMultiplied(int[][] m, int[][]n){
    mRows = m.length;
    mCol = m[0].length;
    nRows = n.length;
    nCol = n[0].length;
    if(nRows == mCol){
        return true;
    }
    return false;
}

public static void main(String[] args) {
    int[][] temp1 = {{1,2,3},{4,5,6}};
    int[][] temp2 ={{1},{2},{3}};
    for(int i = 0; i < mRows; i++){
        for(int j = 0; j < nCol; j++){
            System.out.print(multiplyMatrices(temp1,temp2)[i][j]);
        }
                    System.out.print("\n");
    }

}
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这可以遍历2D数组并打印每个元素。

static final int ROWS = 2;
static final int COLS = 4;

int[][] a2 = new int[ROWS][COLS];

//... Print array in rectangular form
for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
        System.out.print(" " + a2[i][j]);
    }

    System.out.println("");
}