0

I'm currently working with my assignment which requires me to read input from a text file and store into a matrix. Basically I have part of my code here.

    int count = 0 ;
    double[][] matrix = null;

    while ((line = reader.readLine()) != null) 
    {   
        line2 = line.split(" ");

        double[] criteriaWeight = {Double.parseDouble(line2[0]),Double.parseDouble(line2[1]),Double.parseDouble(line2[2]),Double.parseDouble(line2[3])};

        for ( int i = 0 ; i < criteriaWeight.length ; i++ )
            matrix[count][i] = criteriaWeight[i];

        count++;
    }

Now, the logic of what I'm trying to do is that I read data from a text file and then convert it into a double and store into a 2D array (matrix). I managed to read the data from the file. That is error-free.

Now, my problem is at the matrix[count][i] = criteriaWeight[i]; where I get error

Exception in thread "main" java.lang.NullPointerException
at javaapplication2.JavaApplication2.readFile(JavaApplication2.java:42)
at javaapplication2.JavaApplication2.main(JavaApplication2.java:56)
Java Result: 1

Anyone can point to my mistakes here? Thank you very much.

2 Answers 2

2

NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

So, In your code double[][] matrix = null;

You declared and initialized with null.

So when you write

  matrix[count][i]

That is still null. You need to initialize like

 double[][] matrix = new double[x][y];

If you are looking for a dynamic array ,consider using ArrayList

Sign up to request clarification or add additional context in comments.

3 Comments

How about I want the array to be dynamic? I don't know the size of the array yet.
@user3054491, I suppose you could use an ArrayList of ArrayList<Double>. It is not necessarily memory efficient though.
Thansk for the heads up. Thank you very much.
0

How about the following implementation

List<Integer>[] array;
array = new List<Integer>[10];
array[0] = new ArrayList<Integer>(); ....

It will work as dynamic two dimensional array

1 Comment

Thanks for the example. I never used List before. Will look at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.