0

In my task I have 2 classes Kadry(personnel) and Pracownik(worker). Pracownik looks like this (with getters and setters):

public class Pracownik {

private String name;
private String lastName;
private double salary;
private char gender;
private int structure;

public Pracownik( String name, String lastName, double salary, char gender, int structure) {
    this.name = name;
    this.lastName = lastName;
    this.salary = salary;
    this.gender = gender;
    this.structure = structure;

In the class Kadry there are fields private Pracownik[] workers and private int employment (holds actual number of workers), Constructor that initializes the fields. There is also a method that adds a worker to the list, and this point is where i got into troubles, because i keep getting NullPointException. My class Kadry looks like this:

public class Kadry {
private Pracownik[] workers_;
private int employement_;

public Kadry () {
    Pracownik[] workers_ = new Pracownik[100];
    employement_ = workers_.length;
}
public void addWorker(Pracownik p) {
    for (int i = 0; i < 100; i++) {
       if (workers_[i] == null) {
           workers_[i] = p;
           break;
       }
       else System.out.println("List is already full!!!");
    }
}

public static void main(String[] args) {
    Kadry k1 = new Kadry();
    Pracownik Piotr = new Pracownik("Piotr", "Wanjas", 3000.00, 'M', 3);
    k1.addWorker(Piotr);
    System.out.println(k1.workers_[0].getName());

    }
}

The NullPointException shows up at line if (workers_[i] == null) {

  • 1
    `workers_` is null. You create a local variable `workers_` in the `Kadry` constructor, but you don't initialise the instance variable. – khelwood Jun 22 '17 at 19:17
  • this.workers_ = new Pracownik[100]; – Berkley Lamb Jun 22 '17 at 19:19
  • when you are using same variable name for local variable as instance variable then they hide the instance variable inside the block(here your constructor), unless you explicitly reference with "this.variable" .You initialized local variable and its scope is only in the constructor, but the instance variable still takes the default value of null.And you are trying to access element on the null , so it gives NullPointerException – hasha Jun 22 '17 at 19:37
  • In the Kadry constructor, remove `Procownik[]` infront of `workers_`. Otherwise, you are creating a separate local variable in your constructor instead of referring to the field. – Rapid Readers Jun 22 '17 at 19:53

0 Answers0