So for this part of my homework, I need to do matrix multiplication and here is the general criteria:
As far as the computation goes, I had no problem doing it however, my professor says that if any double in the component is .00 it must be represented then as an integer like 24 in a(ij) = a(13) = 24 as you see in the homework example. However, in my case, no matter what I try, I cannot get it to be an integer of 24 without getting rid of the decimal format.
Furthermore, when I print out my result, I start on a new line away from the last output line: "Multiplication of the matrices is: "
Whereas the homework example shows the first row of multiplied matrix on the same line as the output and formatted perfectly for the following rows.
Someone please help. I don't know why my professor is so strict about design over function but I've been trying to figure this out for a few hours and I am stuck.
import java.text.DecimalFormat;
import java.util.Scanner;
public class ProblemFour {
public static void main(String[] args) {
System.out.print("Enter matrix1: ");
Scanner stdin = new Scanner(System.in);
String a = stdin.nextLine();
System.out.print("Enter matrix2: ");
String b = stdin.nextLine();
ProblemFour o = new ProblemFour();
double[][] matrixA = new double[3][3];
double[][] matrixB = new double[3][3];
String[] nums1 = a.split(" ");
String[] nums2 = b.split(" ");
if (nums1.length == nums2.length) {
matrixA = o.makeMatrix(nums1);
matrixB = o.makeMatrix(nums2);
double[][] matrixC = o.multiplyMatrix(matrixA, matrixB);
for (int i = 0; i < 3; i++) {
System.out.println(" ");
if (i == 0) {
System.out.println("Multiplication of the matrices is: ");
}
System.out.println(" ");
for (int j = 0; j < 3; j++) {
System.out.print(matrixC[i][j] + " ");
}
}
} else {
System.out.println("matrix1 column not equal to matrix2 row");
stdin.close();
}
}
public double[][] makeMatrix(String[] nums) {
double[][] matrix = new double[3][3];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
int n = matrix[j].length * i + j;
matrix[i][j] = Double.parseDouble(nums[n]);
}
}
return matrix;
}
public static double[][] multiplyMatrix(double[][] a, double[][] b) {
double totalElem = 0.0;
double[][] multipliedMatrix = new double[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
DecimalFormat df = new DecimalFormat("##.#");
double current = a[i][k] * b[k][j];
double newdf = Double.parseDouble(df.format(current));
totalElem += newdf;
if (k == 2) {
int roundInt = (int) totalElem;
if (totalElem - roundInt == 0.0) {
multipliedMatrix[i][j] = roundInt;
} else {
multipliedMatrix[i][j] = totalElem;
}
totalElem = 0;
}
}
}
}
return multipliedMatrix;
}
}