将成员添加到对象数组

时间:2014-11-28 21:29:36

标签: java arrays class

我想编写一个处理我的数组的类(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();
    }

}

抛出的错误是:

  

线程中的异常&#34; main&#34;显示java.lang.NullPointerException       在ListDePersonnes.addpersonne(ListDePersonnes.java:29)       在LaListe.main(LaListe.java:16)

2 个答案:

答案 0 :(得分:4)

shadowing变量liste。取代

Personne[] liste = new Personne[t]; 

liste = new Personne[t]; 

答案 1 :(得分:2)

Java包含一个更容易进行此类操作的类,List(docs)。

示例用法(来自here):

要在列表中添加元素:

List<Personee> listA = new ArrayList<Peronsee>(); //New ArrayList
listA.add(new Personee("Bob", 29, 165)); //Add element
listA.add(new Personee("Alice", 25, 124)); 
listA.add(0, new Personee("Eve", 34, 136)); //This adds an element to the beginning of the list, index 0.

删除元素:

listA.remove(personee1); //Remove by object
listA.remove(0); //Remove by index

访问/遍历列表:

//access via index
Peronsee element0 = listA.get(0);
Personee element1 = listA.get(1);
Personee element3 = listA.get(2);


//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
  Personee personee = (Personee) iterator.next();
}


//access via new for-loop
for(Personee personee : listA) {
    System.out.println(personee.nom + "," + personee.age + "," + personee.poid);
}