I have 2 classes : Persoana(person) and PersoanaList(to store all the Persoana objects)

Persoana.java:

public class Persoana {
    private String nume;
    private String prenume;
    private ContCurent contCurent;
    private ContDepozit contDepozit;

    public Persoana(String n,String pr,ContCurent cC){//are doar cont curent
        nume=n;
        prenume =pr;
        contCurent=cC;
    }
    public Persoana(String n,String pr,ContDepozit cD){//are doar cont depozit
        nume=n;
        prenume =pr;
        contDepozit=cD;
    }
    public Persoana(String n,String pr,ContCurent cC,ContDepozit cD){//are atat cont curent cat si depozit
        nume=n;
        prenume =pr;
        contCurent =cC;
        contDepozit=cD;
    }
    public String getNume(){
        return nume;
    }
    public String getPrenume(){
        return prenume;
    }
    public void afisare(){
        System.out.println(nume);
        System.out.println(prenume);
        System.out.println(contDepozit.numarCard);
        System.out.println(contDepozit.pin);
        System.out.println(contDepozit.sold);
        contDepozit.getDataScadenta();

    }
    public int getPin(){
        return contCurent.pin;

    }

The PersoanaList file :

public class PersoanaList {

 Persoana[] perslist = new Persoana[20];
int i=1;
public void adauga(Persoana a)
{

    perslist[i]=a;
    i++;


}
public void afisare(){
    for(int j=1;j<=perslist.length;j++)
    {
        perslist[j].afisare();
    }
}
public boolean cautare(String a,int b){
    boolean check=true;
    for(int j=1;j<=perslist.length;j++)
    {

        if(perslist[j].getNume().equals(a) && perslist[j].getPin()==b)
        check= true;
        else
            check= false;

    }
    return check;




}
public int marime(){
    return perslist.length;
}

}

Each Persoana have a name and pin . The method "cautare " will search in array and if exists pin and name.If exists return true(kinda like login);

I have this error :java.lang.NullPointerException Can anyone help me? Please ..

Ps : perslist[j].getNume() - isn't null , neither ..getPin()

有帮助吗?

解决方案

You are getting the NullPointerException (NPE) in one of your loops in the PersoanaList class. For example:

public boolean cautare(String a,int b){
    boolean check=true;
    for(int j=1;j<=perslist.length;j++)
{

    if(perslist[j].getNume().equals(a) && perslist[j].getPin()==b)

Since unless you've completely filled your perslist variable, you'll hit an array item that is null, giving you a NPE when .getName() is called.

After you fix that though, you'll probably hit an ArrayIndexOutOfBoundsException since you are using 1 to n for your array indices. Arrays start at 0 and go to n-1. So for 20 array items, you would reference them as 0 to 19.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top