0

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

5 回答 5

5

您的第二维arr未初始化,您正在调用

arr[index].length
于 2012-06-26T04:55:09.337 回答
1

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

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

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

    我对您的代码进行的唯一修改以使其正常工作是以下行:

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

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

于 2012-06-26T05:08:17.537 回答
0

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

因此,您将不得不分别初始化这些int数组中的每一个。从您从未在程序中的任何位置实际指定第二维的长度这一事实来看,这一点很明显。

于 2012-06-26T05:13:00.420 回答
0

你需要改变——

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

arr[index] = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
于 2012-06-26T05:06:30.913 回答
0

我认为你应该使用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();
    }
}
于 2012-06-26T04:57:18.070 回答