【发布时间】:2015-01-27 13:18:52
【问题描述】:
我想写一个类 (ListDePersonnes) 来处理我的数组,目前我只有两种方法,一种是添加对象,另一种是将数组内容打印到屏幕上。
ListDePersonnes
import java.util.Scanner;
public class ListDePersonnes {
int count,t;
personne liste[];
Scanner s=new Scanner(System.in);
public void initialize() { //
System.out.println("entrer la taille"); //
t = s.nextInt(); // I'm not so sure about this part.
personne[] liste = new personne[t]; //
}
public void addpersonne(){
System.out.println("what is the name?");
String nom= s.next();
System.out.println("what is the age?");
int age= s.nextInt();
System.out.println("what is the weight?");
double poid= s.nextDouble();
liste[count] = new personne(nom,age,poid); // weight is poid in frensh
count++;
}
public void showAll(){
for (int i=0;i<t;i++ ){
System.out.println("name: "+ liste[i].getNom() + " / age: "+liste[i].getAge()+" / poid: "+liste[i].getPoid());
}
}
}
personne
public class personne {
private String nom;
private int age;
private double poid;
public personne(String nom, int age, double poid) {
this.nom = nom;
this.age = age;
this.poid = poid;
}
}
Main
import java.util.Scanner;
public class LaListe {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
ListDePersonnes lper= new ListDePersonnes();
lper.initialize();
lper.addpersonne();
}
}
抛出的错误是:
线程“main”中的异常 java.lang.NullPointerException 在 ListDePersonnes.addpersonne(ListDePersonnes.java:29) 在 LaListe.main(LaListe.java:16)
【问题讨论】:
-
personne[] liste = new personne[t];。您正在隐藏您的类字段变量。应该是liste = new personne[t]; -
伙计们,放轻松。我是新手 :) 大声笑所以变得可怕......只需格式化你的代码并表现出一些努力,人们不会投票或关闭
-
@IslamBouderbala 很高兴你也投了赞成票 :)
-
如果用户填满数组,您可能需要考虑创建一个更大的数组以容纳更多 Personne 的方法。或者使用不同的数据结构,例如 ArrayList,它们使用起来非常简单。
-
@Islam Bouderbala 你的意思是如何从数组中删除人?数组具有静态长度,因此您必须创建长度为
lenght-1的新数组,然后将所有Objects(您要删除的除外)“复制”到新数组。我建议你使用List。