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.
Thrown when an application attempts to use null in a case where an object is required. These include:
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.