I have some trouble handling memory in Java
import java.util.Scanner;
class P4 {
public static void main(String[] args) {
Matrix x=new Matrix(2,4);
Matrix y=new Matrix(2,4);
Matrix a=new Matrix(2,4);
Matrix b=new Matrix(2,4);
Matrix c=new Matrix(2,4);
x=a.input();
y=b.input();
c=x.add(y);
c.display();
}
}
class Matrix{
private int x,y;
double m[][];
Scanner in=new Scanner(System.in);
Matrix(int a1,int b1){
x=a1;
y=b1;
}
public Matrix input() {
double m[][]=new double[x][y];
System.out.println("Enter "+x*y+" elements : ");
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
m[i][j]=in.nextDouble();
}
}
System.out.println("You Entered : ");
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
System.out.printf("%f\t",m[i][j]);
}
System.out.println();
}
return this;
}
public void display() {
System.out.println("Elements in the Matrix are : ");
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
System.out.printf("%f\t",m[i][j]);
}
System.out.println();
}
}
public Matrix add(Matrix n) {
Matrix temp=new Matrix(n.x,n.y);
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
temp.m[i][j]=m[i][j]+n.m[i][j];
}
}
return temp;
}
public Matrix sub(Matrix n) {
Matrix temp=new Matrix(n.x,n.y);
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
temp.m[i][j]=m[i][j]-n.m[i][j];
}
}
return temp;
}
}
In the above code I'm unable to to hold x and y in memory (tried to keep them in reference by using a dummy a and b), as a result I'm unable to call add() which cause the error.
BTW, my output:
Enter 8 elements :
1 2 3 4 5 6 7 8
You Entered :
1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000
Enter 8 elements :
8 7 6 5 4 3 2 1
You Entered :
Exception in thread "main" 8.000000 7.000000 6.000000 5.000000
4.000000 3.000000 2.000000 1.000000
java.lang.NullPointerException
at Matrix.add(P4.java:53)
at P4.main(P4.java:11)