Reputation: 13
I'm trying to implement the matrix multiplication algorithm, but I have an issue dealing with BigInteger
.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Size of Matrix A");
int tamA1 = scan.nextInt();
int tamA2 = scan.nextInt();
System.out.println("Size of Matrix B");
int tamB1 = scan.nextInt();
int tamB2 = scan.nextInt();
BigInteger[][] A = new BigInteger[tamA1][tamA2];
BigInteger[][] B = new BigInteger[tamB1] [tamB2];
BigInteger[][] C = new BigInteger[A.length][B[0].length];
System.out.println("Values of Matrix A");
for (int i = 0; i < tamA1; i++) {
for (int j = 0; j < tamA2; j++) {
A[i][j] = scan.nextBigInteger();
}
}
System.out.println("Values of Matrix B");
for (int i = 0; i < tamB1; i++) {
for (int j = 0; j < tamB2; j++) {
B[i][j] = scan.nextBigInteger();
}
}
if (A[0].length == B.length) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < A[0].length; k++) {
C[i][j] =C[i][j].add(A[i][k].multiply(B[k][j])); // Result
}
}
}
}
System.out.println(" C is equal to: ");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
System.out.print(C[i][j]+" ");
}
System.out.println("");
}
}
Take a look at this output:
Matrix A
2 2
Matrix B
2 2
Values of A
2 2
1 0
Values of B
3 4
5 6
Exception in thread "main" java.lang.NullPointerException
at matrixmultiplication.MatrixMultiplication.main(MatrixMultiplication.java:56)
C:\Users\Luis Miguel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
I don't know why I can do this operation with int
and not with BigInteger
.
Thanks in advance.
Upvotes: 1
Views: 420
Reputation: 64903
The "difference" (or really a similarity, depending on how you think about it) between an array of int
and an array of BigInteger
is that when you make a new array of integers, all the integers exist (and are zero) while a new array of BigInteger
is filled with null
. Of course add
cannot be called on null
.
There are different fixes, for example you could fill the matrix C
with zeros, or you could modify the multiplication so that it does not read from C
at all but instead sums into a local variable which you initialize to zero.
Upvotes: 1