I am currently working on a program that is working with queues and simulates a
ID: 642218 • Letter: I
Question
I am currently working on a program that is working with queues and simulates a grocery store line. However I am having difficulties finishing it up. My main issue is that when I run the program I get a null pointer exception and can't figure out why. Below is the code that I have:
public class GroceryStoreDriver{
public static void main(String[] args){
QueueLinkedList list = new QueueLinkedList();
int queueLength = 0;
int maxLength = 0;
int numServiced = 0;
for(int i = 0; i < 60; i++) {
int r = (int)(Math.random()*4);
if(r == 1){
Customer c = new Customer();
list.add(c);
queueLength ++;
System.out.println("New customer added!! Queue length is now: " + queueLength);
}
if(!list.isEmpty()) {
list.getFirst().decServiceTime();
}
if(list.getFirst().getServiceTime() == 0) { <------------ ******I get the exception here*****
list.remove();
queueLength --;
System.out.println("Customer serviced and removed!! Queue length is now: " + queueLength);
}
if(queueLength > maxLength) {
maxLength = queueLength;
}
System.out.println("-------------------------");
}
}
}
Explanation / Answer
I guess the syntax you are using for generting the radom number is wrong.
int r=(int)(Math.random*4);//starts at 0, so add 1
eg. int r=(int)(Math.random*4)+1;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.