嘿,我有一大段代码应该将 csv 文件的行加载到对象数组中:
public static WarehouseItem[] loadRecords(WarehouseItem[] records) {
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int numRows = 0;
String warehouseItem;
String filename;
filename = ConsoleInput.readLine("Please enter the filename (DataMillion.csv OR DataThousand.csv)");
try {
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
warehouseItem = bufRdr.readLine();
records[numRows] = new WarehouseItem(warehouseItem); //NULL POINTER EXCEPTION HERE
System.out.println(records[0].toString(records[0].columnVals));
while (warehouseItem != null) {
numRows++;
records[numRows] = new WarehouseItem(warehouseItem);
warehouseItem = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e) {
if (fileStrm != null) {
try {
fileStrm.close();
} catch (IOException ex2) {}
}
System.out.println("Error in file processing: " + e.getMessage());
}
main(null);
return records;
}
但是当我运行它时,我得到一个 NullPointerException 就行了
records[numRows] = new WarehouseItem(warehouseItem);
有什么我错过的吗?
这是 WarehouseItem 构造函数 + toString:
public class WarehouseItem {
String[] columnVals;
int numColumns = 5;
public WarehouseItem(String warehouseItem) {
String key, brand, model, price, weightInKG;
int intWeightInKG;
double doublePrice;
StringTokenizer strTok;
strTok = new StringTokenizer(warehouseItem, ",");
key = strTok.nextToken();
brand = strTok.nextToken();
model = strTok.nextToken();
intWeightInKG = Integer.parseInt(strTok.nextToken());
doublePrice = Double.valueOf(strTok.nextToken());
weightInKG = String.valueOf(intWeightInKG);
price = String.valueOf(doublePrice);
String[] columnVals = {key, brand, model, weightInKG, price};
if(columnVals.length != 5)
throw new IllegalStateException("Invalid CSV: not enough columns");
}
public String toString(String[] columnVals) {
return ("Key: " + columnVals[0] + "\n" +
"Brand: " + columnVals[1] + "\n" +
"Model: " + columnVals[2] + "\n" +
"Weight: " + columnVals[3] + "\n" + " kg" +
"Price: " + "$" + columnVals[4] + "\n");
}
}
我的问题是值没有正确存储到数组记录中,我不知道为什么