在2d数组上出错java.lang.NullPointerException

时间:2015-04-13 04:42:05

标签: java arrays parsing nullpointerexception bufferedreader

我一直想弄清楚为什么这行

myArr[line][i] = Integer.parseInt(tmp[i]);

不起作用,我收到此错误java.lang.NullPointerException

我在这里要做的是读取带有BufferedReader的.txt文件的行,看起来像这样,然后将它们拆分并放在一个名为myArr <的双数组上/ p>

1,500,600 2,300,800 3,800,1000 4,200,5000

`

   private static int[][] myArr;
   BufferedReader br = null;    

   BufferedReader br2 = null;   

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));
        //br2 = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));

        //int lines = (int) br2.lines().count();
         //myArr = new int[lines][3];

        int line = 0;
        while((sCurrentLine = br.readLine()) != null){
             String[] tmp = sCurrentLine.split(",");//split the line up into its separate values

             for(int i = 0 ; i < 3 ; i++)
                  myArr[line][i] = Integer.parseInt(tmp[i]);
                  //convert the values into integers and insert them at the matching position
                  //in the array


             line++;
        }

         System.out.println(Arrays.toString(myArr));

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }`

1 个答案:

答案 0 :(得分:3)

取消注释:

//myArr = new int[lines][3];

您没有初始化数组,因此当您尝试填充数组时它会为null。