[英]Adding a member to an array of objects
我想编写一个处理数组的类( 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();
}
}
引发的错误是:
LaListe.main(LaListe.java:16)处ListDePersonnes.addpersonne(ListDePersonnes.java:29)处的线程“ main”中的java.lang.NullPointerException异常
Java提供了一个类,可以更轻松地执行此类操作,即List( docs )。
用法示例(从此处开始 ):
要将元素添加到列表中:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.