elder4222
elder4222

Reputation: 355

A NullPointerException is being thrown but I can't figure out how to fix it.

I have the following code. It is a constructer for a Matrix class. The main thread only calls the constructor, and then prints the matrix (I made a method for it).

public class Matrix{ 
    float [][] mainMatrix; 
    int rows; 
    int columns; 
    public Matrix(){
        System.out.printf("\nInput the number of rows \n") ;
    String rowR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString();
    rows = Integer.parseInt(rowR);
    System.out.printf("\n Input the number of columns \n");
    String columnR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString();
    columns = Integer.parseInt(columnR);
    System.out.printf("Input the rows, seperated by a \" \". Close the row with a \"]\"");
    System.out.println("Warning!!! Inproper input will cause the program to crash!"); 
    for(int r = 0; r < rows; r++){
        Scanner item = new Scanner(System.in);
        System.out.printf("\n["); 
        String[] raw = item.next().replace("]", "").replace("\n", "").split(" ");
        for(int c = 0; c < columns; c++){
            mainMatrix[r][c] = Float.parseFloat(raw[c]);  
        }
    }
    /*Bunch of methods*/ 
} 

For some reason, when the code is run, it returns a NullPointerException, and points to the line:

mainMatrix[r][c] = Float.parseFloat(raw[c]);

If it helps, the output looks like this:

 Input the number of columns 
2

Input the rows, seperated by a " ". Close the row with a "]"Warning!!! Inproper input will cause the program to crash!

[ 2 3] /*\n*/ 
[Ljava.lang.String;@29173efException in thread "main" java.lang.NullPointerException
    at mathProgs.linProg.Matrix.<init>(Matrix.java:51)
    at mathProgs.linProg.MatrixTest.main(MatrixTest.java:10)

the 2, 3, and ] are user inputs. Enter is pressed after the "]"

Upvotes: 0

Views: 115

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503180

The reason is that you haven't initialized mainMatrix. You need something like:

mainMatrix = new int[rows][columns];

Otherwise the variable has its default value of null, so when you try to dereference it (assigning a value to an element of the array) you get the NullPointerException.

Note that unlike in some other languages, once you've created an array object it has a fixed size - you can't just add items to it later. For that, you'd need a List implementation such as ArrayList. Not a problem in this case, as you know how many rows and columns you've got to start with - but worth bearing in mind.

Upvotes: 5

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

You haven't initialized your mainMatrix attribute so its default value will be null thus getting the NPE when using it. Initialize it when you have your row and column variables:

mainMatrix = new float[rows][columns];

Upvotes: 2

Related Questions