Search code examples
javaloopsdeque

java adding objects to ArrayDeque at random intervals


Trying to add objects to a ArrayDeque at random intervals. This is what I have

    for (int i = 0; i <= 100; i ++) {           
        if (window.isEmpty()) {
            Customer customer = new Customer(r.nextInt(10)+1);
            q.add(customer);
            window.beginService();
        }
        else {
            Customer customer = new Customer(r.nextInt(10)+1);
            q.add(customer);
            window.beginService();
            totalCustomers++;
            totalServiceTime += window.serviceTime;
            totalWaitTime += customer.getArrivalTime();
        }
    }

The other methods being used are

public boolean isEmpty() {
    if (serviceTime == 0) {
        return true;
    }
    else 
    return false;
}

public void beginService() {
    if (isEmpty()) {
        serviceTime = r.nextInt(10)+1;
    }
    else
        serviceTime += r.nextInt(10)+1;
}

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

public int getArrivalTime() {
    return arrivalTime;
}

When I print out my customer count it is equal to my clock time, which should not be as customers are added at random intervals of 1-10. Any ideas?


Solution

  • Are you defining your "clock time" as the value of i? If so, I'm not sure why you would expect it and totalCustomers to be different.

    In your for loop, you add a customer regardless of whether or not the windows is empty. After the first time around, the window will never be empty because you are always beginning service which always increments the serviceTime by at least 1.

    So after the first iteration of the loop, the else branch of your if will exclusively be executed and totalCustomers will always increment alongside of i.

    I think you have bigger logic gaps in your code but you haven't been very clear with how you've framed your question or shown your code. It is unclear how serviceTime is declared or what the code is supposed to be doing. You never seem to take an item off of the queue. If you need more help than this you need to put some more effort into your question.