for循环for java中的二维数组

h-r*_*rai 0 java

我想从文件中读取数字行.代码如下,但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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 5

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

arr[index].length
Run Code Online (Sandbox Code Playgroud)