考虑到由于以下错误,我花了一天时间:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
我在下面的代码中实现了上面的所有想法,这就像矩阵乘法的魅力:
import java.util.*;
public class MatmultC
{
private static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
int m = sc.nextInt();
int n = sc.nextInt();
int a[][] = new int[m][n];
arrayreader(a,m,n);
printMatrix(a);
int[][] b = readMatrix();
printMatrix(b);
int[][] c=mult(a,b);
printMatrix(c);
}
public static void arrayreader(int [][] m, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = sc.nextInt();
}
}
}
public static int[][] readMatrix() {
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = sc.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%4d " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static int[][] mult(int a[][], int b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new int[0][0];
if(a[0].length != b.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = b[0].length;
int ans[][] = new int[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
}
}
其中作为输入矩阵,我们有 inC.txt
4 3
1 2 3
-2 0 2
1 0 1
-1 2 -3
3 2
-1 3
-2 2
2 1
在 unix 之类的 cmmd 行中执行命令:
$ java MatmultC < inC.txt > outC.txt
你得到输出
outC.txt
Matrix[4][3]
1 2 3
-2 0 2
1 0 1
-1 2 -3
Matrix[3][2]
-1 3
-2 2
2 1
Matrix[4][2]
1 10
6 -4
1 4
-9 -2