質問

i wrote this method that will add a object to the array but it get me this error

Exception in thread "main" java.lang.NullPointerException

i check all the variables and i think there is nothing null :((

this is my add method

    }
}

the error is in the add_b() method

Exception in thread "main" java.lang.NullPointerException
    at Kindergarten.add_b(Kindergarten.java:39)
    at ClientClass.main(ClientClass.java:22)
役に立ちましたか?

解決

You have error in Kindergarten constructor, instead of initializing arr, you are creating local variable, it should look like this:

public Kindergarten(String name, int numOfbaby) {
    this.name = name;
    arr = new BABY[numOfbaby];
    currnt = 0;
}

secondly, you have an ininite loop, move instruction and reading of input into loop.

another issue is that you have invalid format parameters, just use plain concatenation

last, but not least you are missing System.out.println in display_all method.

loop should start like this:

Kindergarten k = new Kindergarten("baby", 10);

while (true) {
    System.out
            .println("what do you want to do? \n a-add a baby. \n b-search for a baby \n c-Delet a baby. \n d-Display all babys.\n e-how many babys need inoculation \n f-exit");
    char f = read.next().charAt(0);
//(...)
}

他のヒント

First of all, initialization of arr happens only in the second Kindergarten constructor. In the first Kindergarten constructor, arr is a local variable. BABY arr[]=new BABY[numOfbaby];

Also, methods like setarr, setname, setcurrnt are not being used. It will be good if you can clean them up if not used.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top