gpt4 book ai didi

java - 递减队列中存储的值

转载 作者:行者123 更新时间:2023-12-01 15:09:00 25 4
gpt4 key购买 nike

我正在开发一个队列项目,该项目模拟杂货店。在我的程序中,我有一个方法调用,它设置一个随机变量,该变量表示为队列中的客户提供服务所需的时间。总迭代次数为 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
}

最佳答案

Integer 是不可变的,因此将 int 包装在您自己的类中:

class Customer {

int time;

public Customer(int time) {
this.time = time;
}

// getter, setter
}

并定义相应的队列:

Queue<Customer> myQueue = new ...;

实例化一个java.util.Timer;在相应的 java.util.TimerTask 中,使用 for-each 循环遍历 Queue,依次更改或删除每个循环:

for (Customer c : myQueue) { ... }

关于java - 递减队列中存储的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com