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中的一个重要人物,所以我会感激任何简单的帮助。
答案 0 :(得分:2)
当我将对象添加到arraylist
时,我已将评论放在最后一行
你的代码是
for (int i = 0; i < fileArray1.length; i++)
for (int j = 0; j < 4; j++)
fileArray2[i] = fileArray1[i].split("\n", 0);
这意味着您只需将fileArray2
中的值设置为fileArray1.length
但是你在这个数组中读取值
for (int i = 0; i < fileArray2.length; i++)
因此,除非fileArray1.length == fileArray2.length
您将阅读未初始化的值。
我建议你丢弃第二个数组,因为它没有做任何有用的事情并合并两个外部循环,然后你会尝试读取你没写的东西。
for (String humanStr : file.split("#", 0)) {
String[] h = humanStr.split("\n", 0);
madeHumanArrayList.add(new Human(h[0], Integer.parseInt(h[1]),
Float.parseFloat(h[2]), Float.parseFloat(h[3])));
}
最后,除非有充分理由,否则我不会使用float
。我建议使用double
或BigDecimal
,因为这些更精确。