Write your code in the file MatrixOpsjava Consider the follo
Solution
public class MatrixOps {
/**
*
* @param A
* @param B
* @return
*/
public static double[][] multiply(double[][] A, double[][] B) {
int rowsInA = A.length;
int rowsInB = B.length;
int columnsInA = A[0].length; // same as rows in B
int columnsInB = B[0].length;
double[][] C = new double[rowsInA][columnsInB];
if (columnsInA == rowsInB) {
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
} else {
return null;
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class MatrixDriver {
/**
*
* @param fileName
* @return
* @throws IOException
*/
public static double[][] makeMatrix(String fileName) throws IOException {
int nRow = 0;
int nColumn = 0;
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName));
nColumn = br.readLine().split(\" \").length;
if (nColumn !=0){
nRow=nRow+1;
}
// System.out.println(Arrays.toString( br.readLine().split(\" \")));
while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
nRow=nRow+1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println(nRow+\" \"+nColumn);
double[][] matrix = new double[nRow][nColumn];
Scanner sc = new Scanner(new File(fileName));
for (int i = 0; i < nRow; ++i) {
for (int j = 0; j < nColumn; ++j) {
if (sc.hasNextInt()) {
matrix[i][j] = sc.nextInt();
}
}
}
sc.close();
return matrix;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String fileName1;
String fileName2;
System.out.println(\"Enter File Name for Matrix A:\");
fileName1 = sc.nextLine();
System.out.println(\"Enter File Name for Matrix B:\");
fileName2 = sc.nextLine();
System.out.println(fileName1 + fileName2);
double[][] A = makeMatrix(fileName1);
double[][] B = makeMatrix(fileName2);
double[][] C = MatrixOps.multiply(A, B);
for(double[] x:C){
for(double y:x){
System.out.print(y+\" \");
}
System.out.println(\"\");
}
sc.close();
}
}


