java arraylist添加空指针异常
public class Human {
private int age;
private float height;
private float weight;
private String name = new String();
public Human() {
}
public Human(String name, int age, float height, float weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
public Human(Human human) {
this.name = human.getName();
this.age = human.getAge();
this.height = human.getHeight();
this.weight = human.getWeight();
}
public static void writeFile(Human human, OutputStream output) throws IOException {
output.write((human.getName() + "\n").getBytes());
output.write((human.getAge() + "\n").getBytes());
output.write((human.getHeight() + "\n").getBytes());
output.write((human.getWeight() + "\n").getBytes());
}
public static Human readFile(InputStream input) throws IOException {
int temp;
String file = "";
String[] fileArray;
file += (char) input.read();
while ((temp = input.read()) != -1) {
file += (char) temp;
}
fileArray = file.split("\n", 0);
Human madeHuman = new Human(fileArray[0], Integer.parseInt(fileArray[1]), Float.parseFloat(fileArray[2]), Float.parseFloat(fileArray[3]));
return madeHuman;
}
public static void writeArrayListInFile(ArrayList<Human> humans, OutputStream output) throws IOException {
for (int i = 0; i < humans.size(); i++) {
output.write((humans.get(i).getName() + "\n").getBytes());
output.write((humans.get(i).getAge() + "\n").getBytes());
output.write((humans.get(i).getHeight() + "\n").getBytes());
output.write((humans.get(i).getWeight() + "\n").getBytes());
output.write('#');
}
}
public static ArrayList<Human> readArrayListFromFile(InputStream input) throws IOException {
int temp = ' ';
String file = "";
String[] fileArray1;
String[][] fileArray2 = new String[10][];
ArrayList<Human> madeHumanArrayList = new ArrayList<Human>();
file += (char) input.read();
while ((temp = input.read()) != -1) {
file += (char) temp;
}
fileArray1 = file.split("#", 0);
for (int i = 0; i < fileArray1.length; i++)
for (int j = 0; j < 4; j++)
fileArray2[i] = fileArray1[i].split("\n", 0);
for (int i = 0; i < fileArray2.length; i++)
madeHumanArrayList.add(new Human(fileArray2[i][0], Integer.parseInt(fileArray2[i][1]), Float.parseFloat(fileArray2[i][2]), Float.parseFloat(fileArray2[i][3])));//null pointer exception
return madeHumanArrayList;
}
}
虽然我已经初始化了arraylist,但它给了我nullpointer异常。我是一名java高手,所以我非常感谢任何简单的帮助
# 1 楼答案
你的代码可以读取
这意味着您只能将
fileArray2
中的值设置为fileArray1.length
但是你可以读取这个数组中的值,直到
因此,除非
fileArray1.length == fileArray2.length
,否则您将读取未初始化的值我建议您丢弃第二个数组,因为它没有任何用处,并合并两个外部循环,然后您将尝试读取一些您没有写入的内容
最后,除非有很好的理由,否则我不会使用
float
。我建议用double
或BigDecimal
代替,因为它们更精确