繁体   English   中英

使用 for 循环将文件中的数字行读取到二维数组

[英]Read lines of numbers from a file to a 2d array using a for loop

我想从文件中读取数字行。 代码如下,但是IDE显示NullPointerException运行时异常。 不确定我做错了什么。

//reading the contents of the file into an array
public static void readAndStoreNumbers() {
    //initialising the new object
    arr = new int[15][];

    try {
        //create file reader
        File f = new File("E:\\Eclipse Projects\\triangle.txt");
        BufferedReader br = new BufferedReader(new FileReader(f));

        //read from file
        String nums;
        int index = 0;
        while ((nums = br.readLine()) != null) {
            String[] numbers = nums.split(" ");

            //store the numbers into 'arr' after converting into integers
            for (int i = 0; i < arr[index].length; i++) {
                arr[index][i] = Integer.parseInt(numbers[i]);
            }
            index++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你的arr的第二个维度是未初始化的,你正在调用

arr[index].length

出于两个原因,您可能会遇到 NPEX。

  1. 您没有完成对arr的定义 - 在您的代码中,您将arr声明为int arr[][]并不明显;

  2. 即使您有上述条件,您也不会为第二个阵列预留空间。 你现在拥有的是一个锯齿状的数组 您可以在第二个数组中包含您希望在第二个维度中任意长度的元素。

    我对您的代码所做的唯一修改是以下行:

     arr[index] = new int[numbers.length];

    ...在将元素拉入numbers之后,在进入循环之前。

我认为你应该使用StringBuilder ..

//reading the contents of the file into an array
public static void readAndStoreNumbers() {
    //initialising the StringBuffer 
    StringBuilder sb = new StringBuilder();

    try {
        //create file reader
        File f = new File("E:\\Eclipse Projects\\triangle.txt");
        BufferedReader br = new BufferedReader(new FileReader(f));

        //read from file
        String nums;
        int index = 0;
        while ((nums = br.readLine()) != null) {
            String[] numbers = nums.split(" ");

            //store the numbers into 'arr' after converting into integers
            for (int i = 0; i < arr[index].length; i++) {
                sb.append(Integer.parseInt(numbers[i])).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你需要改变 -

for(int i=0; i<arr[index].length; i++) {

arr[index] = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {

Java 没有真正的多维数组。 您使用的实际上是一个 int 数组的数组: new int[n][]实际上创建了一个数组,其中包含n个类型为int[]的对象。

因此,您将不得不分别初始化每个int数组。 从您从未在程序中的任何地方实际指定第二维的长度这一事实来看,这是显而易见的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM