I want to write a class (ListDePersonnes) that handles my array, currently I only have two methods, one to add objects and one to print the array contents to screen.
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();
}
}
The error thrown is:
Exception in thread "main" java.lang.NullPointerException at ListDePersonnes.addpersonne(ListDePersonnes.java:29) at LaListe.main(LaListe.java:16)
personne[] liste = new personne[t];. You are shadowing your class field variable. It should beliste = new personne[t];lenght-1and then "copy" allObjects(except the one you want to remove) to new array. I recommend you to useList.