我现在有点困惑。我使用此函数将2D String数组重写为2D double数组。但是它正在抛出nullpointer异常。 d2中的数据格式为:
String [i] [0/1],其中0和1是格式为“ 0.3343434”的数字。

  public void StringToDouble () {
     unsorted = new double[d2.length][2];

     for(int i = 0; i < d2.length; i++)
    {
        unsorted[i][0] = Double.parseDouble(d2[i][0]);
        unsorted[i][1] = Double.parseDouble(d2[i][1]);
    }

}


当我打印unsorted [0] [0]和[1] [1]时出现错误。

这是完整的代码。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Scanner;


public class LoadAndSort {

String raw;
double [][] data;
String [] datastring;

// 2D CONVERT

String [] d1;
String [][] d2;
double[][] unsorted;
double [][] sorted;
String path = "src/data.dat";


 public LoadAndSort () throws IOException {



    // # Reads file from disk and stores to variable.
    datas = readFile(path);
    // # Splits the content, and sorts it into a huge string with relevant variables.

    // # Splits on newline to order the lines.
    d1 = datas.split("\\r?\\n");
    // # Splits on comma to convert to 2D Array.
    Convert2D();
    // # Mirrors the 2D array because Mikal is gay.
    //MirrorArray();
    //StringToDouble();

    System.out.println(unsorted[0][0]);
    System.out.println(unsorted[0][1]);

}



private static String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */

        return Charset.defaultCharset().decode(bb).toString();
    }
    finally {
        stream.close();
    }
}

public void Convert2D () {

    d2 = new String[d1.length][];
    int r = 0;
    for (String row : d1) {
        d2[r++] = row.split(",");
    }
}

public void StringToDouble () {

    unsorted = new double[d2.length][2];


    for(int i = 0; i < d2.length; i++)
    {
        unsorted[i][0] = Double.parseDouble(d2[i][0]);
        System.out.println(d2[i][0]);

        unsorted[i][1] = Double.parseDouble(d2[i][1]);
    }

}


}


和来自控制台的错误:

 0.00965821033009
 Exception in thread "main" java.lang.NullPointerException
at LoadAndSort.<init>(LoadAndSort.java:48)
at Runner.main(Runner.java:13)

最佳答案

您可以在unsorted(使用StringToDouble)中初始化unsorted = new double[d2.length][2];,但是构造函数中的函数调用当前已被注释掉,因此unsorted将永远不会初始化。

因此它将是null,并且将在此处抛出NullPointerException

System.out.println(unsorted[0][0]);


不确定这是否是唯一的问题,但首先要解决。

09-11 00:37