1

I have two java classes. Schedule is the main class that uses an array of Jobs called deadline. I'm having problems putting anything in array. I have a for loop that reads data from a text file (it works fine) and inserts certain data into deadline. I not successfully creating deadline because whenever I want to start inserting into the array I get a NullPointerException. (The code below the ... obviously isn't what I actually coded, but it is still the same situation.)

It has been a while since I've coded in Java, so I might be just overlooking something simple, but I'm not really sure what it could be... Thanks for any help you can give.

public class Schedule {

    private Job []deadline;
    Schedule (int n){
        Job[] deadline = new Job[n];
    }

    ...
        int n = 7;
        Schedule schedule = new Schedule(n);

        deadline[0] = new Job("A",3,40); // This line won't compile. NullPointerException
}


public class Job {

    private String name;
    private int deadline;
    private int profit;

    Job(String n, int d, int p){
        name = n;
        deadline = d;
        profit = p;
    }

}

1 Answer 1

9

You are shadowing deadline in your constructor, so you don't initialize the class member deadline, but the local one. Change it to:

    private Job []deadline;
    Schedule (int n){
        deadline = new Job[n];
    // ^^ note - no Job[] here
    }
Sign up to request clarification or add additional context in comments.

3 Comments

In other words, deadline gets declared by the class, so you don't need to re-declare it inside the constructor. By doing so, you're actually creating a new variable (with the same name) that only exists inside your constructor.
facepalm I figured it was something stupid like that. Thanks, man. It works now!
happened to all of us :) glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.