存储在队列中的java递减值
我正在做一个队列项目,程序模拟一家杂货店。在我的程序中,我有一个方法调用,它设置了一个随机变量,表示为队列中的客户提供服务所需的时间。总迭代次数为60次,即分钟。假设给第一个客户4分钟的等待时间,我需要能够在每分钟后减少时间,直到时间达到0。我不知道如何减少名为myQueue
的队列中存储的值。有什么建议可以减少每分钟后队列中存储的值吗
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 楼答案
您希望减少存储在队列顶部的Customer对象中的值
最简单的方法是添加一个方法来减少Customer类中的serviceTime
查看与队列中的Customer对象关联的值,可以执行必要的操作
此外,如果您有任何问题,请先尝试向我、您的助教发送电子邮件。=)
# 2 楼答案
Integer
是不可变的,因此在您自己的类中包装一个int
:并定义相应的
Queue
:实例化一个
java.util.Timer
;在相应的java.util.TimerTask
中,对每个循环使用遍历Queue
,依次更改或删除每个循环: