我現在有點困惑。我做了這個函數來將我的2D String數組重寫成一個2D double數組。但它是投射空指針異常。 d2中的數據格式爲: String [i] [0/1]其中0和1是格式爲「0.3343434」的數字。將2D String數組轉換爲2D double
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]);
}
}
我在打印未排序的[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)
爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。將堆棧跟蹤張貼爲[編輯問題](http://stackoverflow.com/posts/15477983/edit)。 – 2013-03-18 13:27:33
錯誤在哪一行? – Sach 2013-03-18 13:28:15
請在'd2'中顯示實際值。 – 2013-03-18 13:28:24