Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here is my code and I need help with the System.out.println in the main method.

ID: 3690546 • Letter: H

Question

Here is my code and I need help with the System.out.println in the main method. I need help with calculating what the output would be. I have already done the system.out.println statements and need help with what to put within it to calculate what each statment says.

import java.util.Queue;
import java.util.List;
import java.util.LinkedList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class BankSim {
    public String arrivalFilePath;
    public int currentTime;

    public class Event {
        public boolean arrival;
        public int start;
        public int span;
     
        public Event() {
            this.arrival = true;
            this.start = 0;
            this.span = 0;
        }
     
        public Event(boolean isArrival, int startTime, int span) {
            this.arrival = isArrival;
            this.start = startTime;
            this.span = span;
        }
     
        public int at() { return start; }
        public boolean isArrival() { return arrival; }
        public int duration() { return span; }
     
        public void getArrivalEvent(Scanner arrivalFile) {
            this.arrival = true;
            this.start = arrivalFile.nextInt();
            this.span = arrivalFile.nextInt();
        }
    }

    public BankSim(String arrivalFilePath) {
        this.arrivalFilePath = arrivalFilePath;
        this.currentTime = 0;
    }

    public static void main(String [] args) {
      SimulationQueue simulation = new SimulationQueue("arrival.txt");
        try {
           simulation.simulate();
           System.out.println("Final Statistics:");
           System.out.println("Total number of people processed:");
           System.out.println("Average amount of time spent waiting:");
           System.out.println("Maximum wait time");
           System.out.println("Minimum transaction time:");
           System.out.println("Maximum transaction time:");
           System.out.println("Maximum line length:");
           System.out.println("Average line length:");
           }
           catch (FileNotFoundException e) {
            System.out.println(e);
        }
    }
    public void insertEvent(Event event, List<Event> eventList) {
        if (eventList.isEmpty()) eventList.add(0, event);
        else if (eventList.get(0).at() < event.at()) eventList.add(event);
        else eventList.add(0, event);
    }
        public void simulate() throws FileNotFoundException {
        Queue<Event> bankQueue = new LinkedList<Event>();
        List<Event> eventList = new LinkedList<Event>();
        Scanner arrivalFile = new Scanner(new File(arrivalFilePath));
        Event newEvent = new Event();
        newEvent.getArrivalEvent(arrivalFile);
        insertEvent(newEvent, eventList);
     
        while (!eventList.isEmpty()) {
            newEvent = eventList.get(0);
            if (newEvent.isArrival()) {
                System.out.printf("Processing an arrival event at time: %d ", newEvent.at());
                processArrival(newEvent, arrivalFile, eventList, bankQueue);
            }
            else
            {
                System.out.printf("Processing an departure event at time %d ", newEvent.at());
                processDeparture(newEvent, eventList, bankQueue);
            }
        }
    }
  

    public void processArrival(Event newEvent, Scanner arrivalFile, List<Event> eventList, Queue<Event> bankQueue) {
        boolean atFront = bankQueue.isEmpty();
        bankQueue.add(newEvent);
        eventList.remove(0);
        if (currentTime < newEvent.at()) currentTime = newEvent.at();
     
        if (atFront) {
            insertEvent(new Event(false, currentTime+newEvent.duration(), 0), eventList);
        }
     
        if (arrivalFile.hasNext()) {
            Event event = new Event();
            event.getArrivalEvent(arrivalFile);
            insertEvent(event, eventList);
            System.out.println("Simulation Begins");
          
        }
    }

    public void processDeparture(Event newEvent, List<Event> eventList, Queue<Event> bankQueue) {
        bankQueue.remove();
        eventList.remove(0);
        if (currentTime < newEvent.at()) currentTime = newEvent.at();
     
        if (!bankQueue.isEmpty()) {
            if (currentTime < bankQueue.peek().at()) currentTime = bankQueue.peek().at();
            insertEvent(new Event(false, currentTime+bankQueue.element().duration(), 0), eventList);
        }
    }
}

Explanation / Answer

import java.io.*;
public class Simulator
{
    private double aveArrival; //averageArrival time of customers
    private double aveService; //averageService time of customers
    private double timeLimit;   //simulation timelimit
    private int servers;    //# of tellers in the bank
    private boolean showSketch; //showSketch
    private double curTime; //current time of the simulation
    private PrintWriter out;    //Output writer to file "out.txt"

    //The following variables could have been initialized in a method and passed through paramteres,
    //however, for ease of access and use I used instance variables
    private int curCustomer=0; //integer representation of the customer at the head of the queue
    private int curNumOfCustomers=0; //# of customers in queue
    private int customersServed=0; //# of customers that have left the queue
    private int customers=0;    //total # of customers through the doors
    private int nowait=0; //# of customers who didn't have to wait in the queue
  
    private static int ARRIVAL =1; //Event = Arrival
    private static int DEPARTURE = 0; // Event=Departure
  
    private Queue<Event> eventList; //eventlist (only holds at most 1 Arrival and 1 Departure event at a time)
    private Queue<Event> bankQueue; //bankQueue (a list of arrival events to be processed)
    private Queue<Customer> customerQueue;//customerList (a list of all customers that have walked through the door)
                                            //earliest customer=head of the list
  
    private int x=0;                        //# of Arrival events processed
    private int y=0;                        //#of Departure events processed
  
    /**Constructor,
    */
    public Simulator(double avgInterarrivalTime, int numberOfServers, double avgServiceTime )
    {
        aveArrival = avgInterarrivalTime;
        aveService = avgServiceTime;
        servers = numberOfServers;
      
    }
    /**
     * Generates random numbers with an exponential differentiation from a desired value
     */
    public double exponentialDistribution(double average)
    {
        double uniformDistribution = Math.random();
        return -average * Math.log(uniformDistribution);
    }
     */
    public void run(double simTimer, boolean trace){
        Greet();//output greeting message/instructions to user
      
        //initialize queues
        bankQueue = new Queue();
        eventList = new Queue();
        customerQueue = new Queue();
        //set simTimeLimit
        timeLimit=simTimer;
        //set showSketch to true or false
        showSketch=trace;
      
        //initialize output writer
        try{
            out = new PrintWriter("out.txt");//text file for sketch

        }
        catch(IOException e){}
      
        //create first arrival event and set clock to first arrival time      
        curTime = exponentialDistribution(aveArrival);
        Event firstArrival = new Event(curTime, ARRIVAL,exponentialDistribution(aveService));
        eventList.addPriority(firstArrival);
      
        //while simulation has not surpassed its timelimit...
        while(curTime<timeLimit)
        {
           //get next event from eventList
            Event newEvent = eventList.peek();
            writeToFile("Clock: "+newEvent.getTime());//write time
          
            //if event == Arrival Event
            if(newEvent.getType()== ARRIVAL)
            {
                x++; //increment the #of Arrival Events processed
                writeToFile("Processing Arrival Event #"+x); //write Arrival Event #
              
                customers++;    //incrememnt # of total customers that have walked through the door
                //curCustomer=customers;
              
                processArrival(newEvent, eventList, bankQueue);//processArivalEvent
                customerQueue.arrive(new Customer(newEvent.getTime()));//add customer to customer list
                //paramter newEvent.getTime()=time that the customer entered the bank
            }
            //if event == Departure Event
            else
            {
               y++; //incrememnt the #of Arrival Events Processes
               writeToFile("Processing Departure Event #"+y);//write Departure Event
               curNumOfCustomers=customers-customersServed;//determine the customers left to be serviced
               curCustomer=customers-curNumOfCustomers+1;//determine the customer at the head of the line
               //determine the time that current customer has been waiting in queue
               //(Time at which customer became the head of the line-time of arrival)
               customerQueue.getLink(curCustomer-1).setWaitTime(customerQueue.getLink(curCustomer-2));
               //process Departure Event
               processDeparture(newEvent, eventList, bankQueue);
            }
            //update current Time of simulation
             curTime = eventList.peek().getTime();
           
             writeToFile("");//write newLine

        }
        //at the end of the simulation there may be customers who are still waiting in the queue
        for(int j=0; j<bankQueue.length(); j++)
        {
            if(customerQueue.getLink(customers-j).getDeparture()==0)
            {
                //for each customer that has not been serviced update their waitting time
                customerQueue.getLink(customers-j).setWaitTime(timeLimit);
            }
        }
        //Write stats to the out.txt file
        printStats();
        out.close(); //close output writer
      
    }
    public void processArrival(Event e, Queue<Event> eventList, Queue<Event> bankQueue)
    {      
        boolean empty = bankQueue.empty();//is the bankQueue.empty()
        bankQueue.arrive(e); //add arrival event to bankqueue
        eventList.leave(); //remove arrival event from eventList
        Event newDeparture; //decalre newDeparture event

        writeToFile("Customer" +customers+" enters the bank"); //write arrival event
        //if bankqueue is empty
        if(empty)
        {
           //line is empty so service can begin right away
           //departure event will occure at (current time+servicetime of customer)
           newDeparture = new Event(curTime+e.getServiceTime(), DEPARTURE);
           //add departure event into eventlist
           eventList.addPriority(newDeparture);
           writeToFile("     and is immediately served at "+curTime);//write to out.txt
         

           nowait++;//increment #of customers who did not have to wait in queue
        }
        Event newArrival = new Event(exponentialDistribution(aveArrival)+curTime,ARRIVAL,exponentialDistribution(aveService));

        //if eventlist is empty
        if(eventList.empty())
        {
            //add to list
            eventList.arrive(newArrival);
        }
        //if eventList is not empty
        else
        {
            if(newArrival.compareTo(eventList.peek())==0)
            {
                //if new Arrival event occurs after the next departure event then add Arrival event to
                //end of eventList
               eventList.arrive(newArrival);
            }
            else
            {
                //if new Arrival event occurs before the next departure then add Arrival event
                //to the front of the eventlist

               eventList.addPriority(newArrival);
               curCustomer--; //logic
            }

        }
        writeToFile("");//write newLine
    }
    public void processDeparture(Event e, Queue<Event> eventList, Queue<Event> bankQueue)
    {
      
        writeToFile("Customer "+curCustomer+" leaves ");//write departure event
        bankQueue.leave(); //remove arrival event that instantaneated this departure event from the queue
        customerQueue.getLink(curCustomer-1).processCustomer(curTime);//set departure time for current
                                                //customer being departed
      
        eventList.leave();//remove departure event eventList
        Event newDeparture;//declare new dewparture event for new head of line customer
        customersServed++; //incrememnt # of customers served
        //if queue is not empty
        if(!bankQueue.empty())
        {
         
            //create a new departure event for the current customer at the front of queue  
            newDeparture = new Event((curTime+eventList.peek().getServiceTime()), DEPARTURE);

          
            if(newDeparture.compareTo(eventList.peek())==0)
            {
                eventList.arrive(newDeparture);
                //if new departure event occurs after the next arrival event add to end of eventList

            }
            else
            {
                eventList.addPriority(newDeparture);
                //if new departure event occurs before the next arrival event add to the front of the eventList

            }
          
        }
    }
    public void printStats()
    {
        double total=totalWaitingTime();//calculate total waiting time among all customers
        out.println("Total number of customers coming through the doors: "+customers);
        out.println("Customers Served(including those being served at end of simulation): "+(customers-curNumOfCustomers+1));
        out.println("Customers who did not hve to wait: "+nowait+" (%" +((nowait/(double)customers)*100)+")");
        out.println("Total wait time(including those who have not been serviced yet): "+total);
        out.println("Avergae waiting time: "+(total/customers));
        out.println("People still in Queue: "+(bankQueue.length()));
    }
    public double totalWaitingTime()
    {
        //for all customers in the list sum their waiting times together
        double total=0;
        for(int i=0; i<customerQueue.length(); i++)
        {
            total+=(customerQueue.getLink(i).getWaitTime());
        }
        return total;
    }
  
    //printed at beginning of simulation
    public void Greet()
    {
        System.out.println(" ");
        System.out.println("This Simulator works only for 1 teller at the bank");
        System.out.println("The sketch, if you choose to view it, will be located in a file "out.txt" ");
        System.out.print("located in your local directory after completion");
        System.out.println();
        System.out.println();
      
      
    }
    public void writeToFile(String s)
    {
        if(showSketch)
        {
            out.println(s);
        }
    }
  
}


Customer.java
public class Customer
{
  
    private double arrival=0; //arival time
    private double departure=0; //departure time
    private double waittime=0; //time waiting in queue

    //constructor, set arrival time
    public Customer(double x)
    {
        arrival = x;
    }
    //processCUstomer
    //initializes departure of customer from the queue
    public void processCustomer(double x)
    {
        departure = x;
    }
    //toString
    public String toString()
    {
        return "arrival: "+arrival+", departure: "+departure+ ", waitTime: "+waittime;
    }
    //returns arrival time
    public double getArrival()
    {
        return arrival;
    }
    //returns departure time
    public double getDeparture()
    {
        return departure;
    }
    public void setWaitTime(Customer other)
    {
      
        waittime=other.getDeparture()-getArrival();//determine waiting time
        if (waittime<0) //if this customer did not have to wait for other customer then set waittime to 0
        {
            waittime=0;
        }
    }
    public void setWaitTime(double time)
    {
        waittime = time-getArrival();
    }
    //return waittime;
    public double getWaitTime()
    {
        return waittime;
    }

}

Event.java
public class Event
{
    private double occurenceTime; //time that event occured
    private int type;    //type of event- arrival/departure
    //for arrival event only
    private double serviceTime; //how long the customer will be at the teller
  
    private static int ARRIVAL = 1;
    private static int DEPARTURE=0;
    public Event(double time, int type)
    {
        this.occurenceTime=time;
        this.type = type;
        serviceTime=0;
    }
    //constructor for arrival event
    public Event(double time, int type, double serviceTime)
    {
        this.occurenceTime=time;
        this.type = type;
        this.serviceTime=serviceTime;
    }
    //returns type of event
    public int getType()
    {
        return type;
    }
    //returns time that event was instantaniated
    public double getTime()
    {
        return occurenceTime;
    }
    //determines which event occured before the other one
    public int compareTo(Event e)
    {
        if(e.getTime()>= occurenceTime){return 1;} //if event e occurs after this then return 1
        else{return 0;}
      
    }
    //set occurence time
    public void setTime(double time)
    {
        occurenceTime=time;
    }
    //return servicetime
    public double getServiceTime()
    {
        return serviceTime;
    }
    //toString
    public String toString()
    {
        return("Time: "+occurenceTime+", Duration:"+serviceTime+", Type "+type);
    }

}

LinkEntry.java
public class LinkEntry<E> {
   protected E element; // The entry's data.

   protected LinkEntry<E> link; // The link to the next entry.

   // Create a new link entry.
   public LinkEntry(E element, LinkEntry<E> link) {
       this.element = element;
       this.link = link;
   } // LinkEntry constructor

   // Return the element of the link entry.
   public E getElement() {
       return element;
   } // getElement method

   // Return the link to the next link entry.
   public LinkEntry<E> getLink() {
       return link;
   } // getLink method

   // Set the link to the next link entry.
   public void setLink(LinkEntry<E> newLink) {
       link = newLink;
   } // setLink method
} /* LinkEntry class */


Queue.java
import java.io.*;
public class Queue<E>{
    //circular linked queue
    public LinkEntry<E> back; //the entry point to the queue is the back of the queue
    private static int LIMIT = 100;//limit is 31
    public int size; //current size of the queue
  
    // Create a new Queue object. The queue is empty to start.
    public Queue()
    {
        back=null;
        size=0;
    }

    // Add element to the rear of the queue. The queue must not be full.
    public void arrive(E element)
    {
        LinkEntry<E> newLink;
        newLink = new LinkEntry(element,back); //initialize newLink to point to back
        if(empty())
        {
            newLink.setLink(newLink);//link newLink to itself if queue is empty
        }
        else if(size>=LIMIT)
        {
             throw new QueueException("QueueException on arrive: Queue reached capacity");
        }
        else//add to back of queue
        {
           newLink.setLink(back.getLink());//set newLink.link to the first element
           back.setLink(newLink); //set back.link to newLink
        }
        back=newLink; //back=newLink
        size++;
     
    }
    public void addPriority(E element)
    {
        LinkEntry<E> newLink;
        newLink = new LinkEntry(element, back);//intialize newLink
        if(empty())
        {
            newLink.setLink(newLink);//if empty link newLink to itself
        }
        else if(size>=LIMIT)
        {
             throw new QueueException("QueueException on arrive: Queue reached capacity");
        }
        else//add to front of list
        {
            newLink.setLink(back.getLink());//newLink.link=first
            back.setLink(newLink);//back.setLink=newLink
        }
        back = newLink.getLink(); //back = old first link
        size++;
    }
    E leave()
    {
        //as long as queue is not empty
       if(!empty())
       {
           LinkEntry<E> firstLink = back.getLink();//get the first link in the queue
           if(firstLink==back)//only one element in the queue?
           {
               back = null;//set queue to empty state
             
           }
           else
           {
               back.setLink(firstLink.getLink());//remove first link from the queue by
                                    //delinking it
             
           }
           size--;//decreent size
           return firstLink.getElement();
       }//else...if queue empty
       else{
           throw new QueueException("QueueException on dequeue: Queue empty");
       }
     
    }
    E peek()
    {
       if(!empty())//return first link
       {
           LinkEntry<E> firstLink = back.getLink();
           return firstLink.getElement();
       }
       else{
           throw new QueueException("QueueException on peek: Queue empty");
       }
    }

    // Return number of elements in the queue.
    int length() {return size;}

    // Return true if the queue contai ns no elements.
    boolean empty() {
        return back==null;
    }

    // Return true if the queue cannot hold any more elements.
    boolean full() {return size>LIMIT;}
   //returns the element belonging to the link at the specific location in the queue
    public E getLink(int x)
    {
        LinkEntry<E> first = back.getLink();//first = first link in the list
        for(int i=0; i<x; i++)
        {
            first=first.getLink();//first=first.link
        }
        return first.getElement();
    }

} /* Queue class */


QueueException.java
public class QueueException extends RuntimeException
{


    public QueueException(String s)
    {
        super(s);
    }

}

out.txt
Clock: 6.848074647291271
Processing Arrival Event #1
Customer1 enters the bank
     and is immediately served at 6.848074647291271


Clock: 11.568056953984371
Processing Departure Event #1
Customer 1 leaves

Clock: 38.17398928347095
Processing Arrival Event #2
Customer2 enters the bank
     and is immediately served at 38.17398928347095


Clock: 39.29882734580617
Processing Arrival Event #3
Customer3 enters the bank


Clock: 39.5509885589716
Processing Departure Event #2
Customer 2 leaves

Clock: 43.704019199024835
Processing Arrival Event #4
Customer4 enters the bank


Clock: 45.785881296116216
Processing Departure Event #3
Customer 3 leaves


Clock: 50.8078238025398
Processing Departure Event #5
Customer 5 leaves

Clock: 53.167128372205376
Processing Arrival Event #6
Customer6 enters the bank
     and is immediately served at 53.167128372205376


Clock: 53.189750446275134
Processing Departure Event #6
Customer 6 leaves

Total number of customers coming through the doors: 6
Customers Served(including those being served at end of simulation): 6
Customers who did not hve to wait: 4 (%66.66666666666666)
Total wait time(including those who have not been serviced yet): 2.3340233102568178
Avergae waiting time: 0.389003885042803
People still in Queue: 0

BankSimulator.java

import java.io.*;
import java.util.*;

public class BankSimulator {
   public static void main(String args[]) throws IOException,
           NumberFormatException {
       Scanner reader = new Scanner(System.in);

       double avgInterarrivalTime;
       int numberOfServers;
       double avgServiceTime;
       double timeLimit;
       boolean tracing;

       String line;

       System.out.print("Simulation of service for people at a service ");
       System.out.println("counter at a bank");
       System.out.println();
       System.out.println("Please give these parameters for the simulation: ");

       System.out.print("Average time between arrivals: ");
       avgInterarrivalTime = reader.nextDouble();

      
       numberOfServers = 1;

       System.out.print("Average time to serve a customer: ");
       avgServiceTime = reader.nextDouble();

       System.out.print("Time limit for simulation: ");
       timeLimit = reader.nextDouble();

       System.out.print("Show trace (y or n): ");
       line = reader.next();
       if (line.equals("y")) {
           tracing = true;
       } else {
           tracing = false;
       }

       // Create a new simulator object with the simulation parameters.
       Simulator simulator = new Simulator(avgInterarrivalTime,
               numberOfServers, avgServiceTime);

       // Run the simulation for the specified length of time.
       simulator.run(timeLimit, tracing);
   } // main method
} /* BankSimulator class */


output
Simulation of service for people at a service counter at a bank

Please give these parameters for the simulation:
Average time between arrivals: 10
Average time to serve a customer: 5
Time limit for simulation: 5
Show trace (y or n): y

This Simulator works only for 1 teller at the bank
The sketch, if you choose to view it, will be located in a file "out.txt"
located in your local directory after completion

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote