0

我现在有点困惑。我制作了这个函数来将我的二维字符串数组重写为二维双精度数组。但它正在投射空指针异常。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)
4

2 回答 2

1

unsortedStringToDouble(with unsorted = new double[d2.length][2];) 中进行了初始化,但构造函数中的函数调用当前已被注释掉,因此unsorted永远不会被初始化。

因此它将是null并且NullPointerException将在这里抛出:

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

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

于 2013-03-18T14:02:20.757 回答
1

您还可以使用 Java 8 中的 Streams API

Double[][] c = Arrays.stream(stringArray).map(
                a -> Arrays.stream(a).map(
                        b -> Double.valueOf(b)
                        ).toArray(Double[]::new)
                ).toArray(Double[][]::new);
于 2018-01-20T15:53:46.877 回答