Reputation: 183
I have an Class called Process and a Class Called Event. Process has a list of Events as one of its attributes. I am reading a file and populating the Process attributes and the Event attributes but when I try to add the Event to the events list of the Process object I get NullPointerException. I have more experience in C# but I have to do this in Java. This is what a line in the file looks like:
0 1 CPU 10 IO 3 CPU 50 IO 3 CPU 10
These are the classes:
public class Process {
int arrivalTime;
int priority;
LinkedList<Event> events;
}
Event.java,
public class Event {
String type;
int duration;
}
FCFS.java,
public class FCFS{
public static void main(String[] args) {
List<Process> readyQueue = new LinkedList<Process>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("path.txt"));
String line = reader.readLine();
while (line != null) {
String[] arr = line.split(" ");
Process process = new Process();
process.arrivalTime = Integer.parseInt(arr[0]);
process.priority = Integer.parseInt(arr[1]);
for(int i = 2; i < arr.length; i = i + 2) {
Event event = new Event();
event.type = arr[i];
event.duration = Integer.parseInt(arr[i+1]);
process.events.add(event);
}
readyQueue.add(process);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 85
Reputation: 134
You have not initialized the events
list. Either initialize it in the Process
class itself to an empty list or after creating Process
object.
In Java, if you do not initialize a Class type, it defaults to null.
Upvotes: 1
Reputation: 153
I guess it is due to not initializing the events. can you try doing the below
public class Process {
int arrivalTime;
int priority;
LinkedList<Event> events = new LinkedList();
}
Upvotes: 1