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

标签 java arrays multidimensional-array integer

我想从文件中读取数字行。代码如下,但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

关于java - 使用 for 循环将文件中的数字行读取到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11200930/

相关文章:

java - Android:在不延迟 Activity 的情况下在后台运行一个线程

java - GCM 推送消息一直保存在服务器上,直到新消息到达

java - 如何在另一个json中的json中获取json?

arrays - 数组中的 Mango 搜索

多次调用malloc

php - 如何从 PHP 中的多维数组中删除空值?

java - 无法将图形应用于 if 语句

java - 将新引用附加到数组?

php - 多维数组到哈希

c - 解决指向字符串的指针中的段错误