I have a class Matrix which contains the class definition:
import java.util.Scanner;
public class Matrix {
private int[][] matrix;
//construct matrix with given number of rows and columns
public Matrix(int n, int m){
matrix = new int[n][m];
}
//input values into matrix
public void readMatrix(){
Scanner input = new Scanner(System.in);
for (int r = 0; r < matrix.length; r++){
for (int c = 0; c < matrix[r].length; c++){
matrix[r][c] = input.nextInt();
}
}
}
//display values of matrix
public void displayMatrix(){
for (int r = 0; r < matrix.length; r++){
for (int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.print("\n");
}
}
}
and a class MatrixApp which contains the main:
import java.util.Scanner;
public class MatrixApp {
public static void main(String[] args) {
Matrix m1 = null; //create matrix m1
promptMatrix(m1); //ask for data for m1 from user
m1.displayMatrix(); //display m1
}
private static void promptMatrix(Matrix m) {
Scanner input = new Scanner(System.in);
int rows, columns;
//ask for number of rows
System.out.print("Enter the number of rows: ");
rows = input.nextInt();
//ask for number of columns
System.out.print("Enter the number of columns: ");
columns = input.nextInt();
//create matrix
m = new Matrix(rows, columns);
//ask for matrix data
System.out.println("Enter matrix: ");
m.readMatrix();
}
}
I get the Null Pointer Exception error on m1.displayMatrix()
. I guess that is because nothing has been stored in m1 although I have passed m1 to the method promptMatrix. Why is that and how can I solve that, please?