[英]How to store data read from a file into 2D array
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
). 现在,我正在尝试做的逻辑是我从文本文件中读取数据,然后将其转换为double
并存储到2D数组( 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];
现在,我的问题出在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. 当应用程序在需要对象的情况下尝试使用null时抛出。 These include: 这些包括:
So, In your code double[][] matrix = null;
所以,在你的代码中double[][] matrix = null;
You declared and initialized with null
. 您使用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
如果您正在寻找动态数组,请考虑使用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 它将作为动态二维数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.