如何存储从文件到二维数组中读取数据 [英] How to store data read from a file into 2D array

查看:167
本文介绍了如何存储从文件到二维数组中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在用我的任务要求我从一个文本文件读取输入并存储成矩阵工作。基本上,我有我的code这里的一部分。

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.

现在,我的问题是在矩阵[计数] [i] = criteriaWeight [I]; 从哪里获得误差

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.

推荐答案

NullPointerException异常

当应用程序试图在需要对象的地方使用null时,抛出该异常。这些措施包括:

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


  • 调用null对象的实例方法。

  • 访问或修改null对象的字段。

  • 以空的长度,就好像它是一个数组。

  • 访问或修改空的插槽,就好像它是一个数组。

  • 投掷空,好像它是一个Throwable的值。

所以,在你的code 双击[] []矩阵= NULL;

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

您宣布与初始化。

所以,当你写

  matrix[count][i]

这仍然是空。您需要初始化像

That is still null. You need to initialize like

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

如果你正在寻找一个动态数组,可以考虑使用的ArrayList

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

这篇关于如何存储从文件到二维数组中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆