问题
I'm working on a queue project where the program is simulating a grocery store. In my program, I have a method call that sets up a random variable that represents the time that it takes to service the customer in queue. The total iterations are 60, signifying minutes. Say if the first customer is given a 4 minute wait time, I need to be able to decrement the time after each minute until it reaches 0. I cannot figure out how to decrement the value stored in the queue named myQueue. Any suggestions how I can decrease the value stored in the queue after each minute?
import java.util.*;
import java.util.Random;
public class GroceryStore{
public static void main (String[] args){
int newCust=0; //to hold random variable 1-4 for 25% chance of new customer
Queue<Integer> myQueue = new LinkedList<Integer>(); //instantiates new queue
int wait = 0;
int numCust = 0; //holds counter for number of customer
for (int i = 1; i <= 60; i++) //iterator to cycle through 60 minutes
{
Random randomNum = new Random();
newCust = randomNum.nextInt(4)+1; //gives random #1-4, if 1, new cust added
if(newCust == 1) //if statement to execute code if new cust added
{
Customer cust = new Customer();
wait = cust.getServiceTime(); //stores wait time in variable
myQueue.add(wait); //adds customer to the queue by wait time
System.out.println("New customer added to queue, queue length is now " + myQueue.size());
}
if(myQueue.isEmpty()) //if to check if queue is empty and skip other conditionals
System.out.println("-----------");
else if(myQueue.peek()==0) //if top of queue is at 0, remove from queue
{
myQueue.remove();
System.out.println("Customer removed");
}
else
//THIS IS WHERE I AM TRYING TO DECREASE THE VALUE IN THE TOP QUEUE
}
回答1:
Integer is immutable, so wrap an int in your own class:
class Customer {
int time;
public Customer(int time) {
this.time = time;
}
// getter, setter
}
and define a corresponding Queue:
Queue<Customer> myQueue = new ...;
Instantiate a java.util.Timer; in the corresponding java.util.TimerTask, iterate through the Queue using a for-each loop, altering or removing each in turn:
for (Customer c : myQueue) { ... }
回答2:
Your wanting to decrement a value stored in the Customer object that is located at the top of the queue.
The easiest way would be to add a method to reduce the serviceTime within the Customer class.
public decServiceTime() {
serviceTime--;
}
Looking at the value associated to the Customer object sitting in the queue you can perform the actions necessary.
Also if you have any questions you should first try sending me, your TA an email. =)
来源:https://stackoverflow.com/questions/12557550/decrementing-value-stored-in-a-queue