Reputation: 776
I am writing a program that takes in input various lecture requests that need to be scheduled. The lectures have start time and an end time. The requirement is to schedule the maximum number of lectures. (The algorithm is to schedule them by end time and select the non overlapping lectures--Greedy Strategy). In order to do so I have a "lecture" class and a "LectureScheduling" class. I create a input array (of lectures). Then I request the user to input the various requests. However I am getting the error "Exception in thread "main" java.lang.NullPointerException". Kindly help. Thank you. PS: I have the error excatly at the line "input[i].time[0] = in.nextInt();" The exact error is: Exception in thread "main" java.lang.NullPointerException at lecturescheduling.LectureScheduling.main(LectureScheduling.java:116)
// The lecture class.. time[0] is start time and time[1] is end time of the lecture
class lecture{
int[] time= new int[2];
lecture (int a, int b){
time[0]=a;
time[1]=b;
}
}
// Part of LectureScheduling Class
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of lectures ");
int arraylength = in.nextInt();
lecture [] input= new lecture[arraylength] ;
for (int i=0; i<arraylength; i++){
System.out.println("Input start time of lecture "+ i);
input[i].time[0] = in.nextInt();
System.out.println("Input end time of lecture "+ i);
input[i].time[1] = in.nextInt();
System.out.println();
}
input=SortByStartTime(input);
input=CreateSchedule(input);
PrintSchedule(input);
}
Upvotes: 2
Views: 639
Reputation: 178451
When allocating an array of objects, you are actually only allocating the references, and not the object itself (lecture [] input= new lecture[arraylength] ;
does not create objects of type lecture
, unlike value type languages such as C++). Thus when you access:
input[i].time[0] = in.nextInt();
Without to first create an instance of lecture
for input[i]
, you get an NPE.
To solve it, you need to use the new
operator on each object of lecture
before you try to access it (assuming the empty constructor is visible and defined):
input[i] = new lecture();
P.S. There is a convention in java that type names (such as lecture
, which is a type) - start with upper case letter. So I would recommend renaming lecture
into Lecture
.
Upvotes: 6