Question

Do in java file Queues are often used to simulate the flow of people, cars, airplanes, transactions, and so on. Write a progr
ems // - // put public void insert (long j) item at rear of queue // if (rear == maxSize-1) deal with wraparound rear = -1; q
return (nItemsw0); // true public boolean is Full if queue is full return (nItems==maxSize); //---- 1 public int size() numbe
Х project2.docx /// class QueueApp public static void main(String[] args) Queue theQueue = new Queue (5); // queue holds 5 it

please explain all the steps. I need it ASAP.
i will give u good ratings.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here i am providing the code. Hope it helps. please give me a like it helps me a lot.

// Queue.java

public class Queue {

      private int maxSize;

      private long[] queArray;

      private int front;

      private int rear;

      private int nItems;

      // --------------------------------------------------------------

      public Queue(int s) // constructor

      {

            maxSize = s;

            queArray = new long[maxSize];

            front = 0;

            rear = -1;

            nItems = 0;

      }

      // --------------------------------------------------------------

      public void insert(long j) // put item at rear of queue

      {

            if (rear == maxSize - 1) // deal with wraparound

                  rear = -1;

            queArray[++rear] = j; // increment rear and insert

            nItems++; // one more item

      }

      // --------------------------------------------------------------

      public long remove() // take item from front of queue

      {

            long temp = queArray[front++]; // get value and incr front

            if (front == maxSize) // deal with wraparound

                  front = 0;

            nItems--; // one less item

            return temp;

      }

      // --------------------------------------------------------------

      public long peekFront() // peek at front of queue

      {

            return queArray[front];

      }

      // --------------------------------------------------------------

      public boolean isEmpty() // true if queue is empty

      {

            return (nItems == 0);

      }

      // --------------------------------------------------------------

      public boolean isFull() // true if queue is full

      {

            return (nItems == maxSize);

      }

      // --------------------------------------------------------------

      public int size() // number of items in queue

      {

            return nItems;

      }

      // --------------------------------------------------------------

      public void display() // display content of queue

      {

            // System.out.println("Array: " +Arrays.toString(queArray));

//          if (nItems < 1) {

//                System.out.println("Array: " + Arrays.toString(queArray));

//                System.out.println("Queue: ");

//                return;

//          }

//          System.out.println("Array: " + Arrays.toString(queArray));

//          System.out.print("Queue: ");

            int ft = front;

            for (int i = 1; i <= nItems; i++) {

                  System.out.print(queArray[ft] + " ");

                  ft = (ft + 1) % maxSize;

            }

            System.out.println();

      }

} // end class Queue

/**

* This class simulates a Checker at a Store.

* Assumption: No checker will take more than 10 minutes to process a customer.

*/

import java.util.Random;

public class Checker {

      // Instance variables

      private Queue queue;

      private int processingTime; // Processing time for one customer, vary as per

                                                // the customer

      private int startTime; // Time when the current customer arrived at the

                                          // checker

      private Random random;

      /**

      * Constructor

      *

      * @param maxLL

      *            - max line length at the checker

      */

      public Checker(int maxLL) {

            queue = new Queue(maxLL);

            startTime = -1;

            processingTime = -1;

            random = new Random();

      }

      /**

      * Displays the line at this checker

      */

      public void display() {

            queue.display();

      }

      /**

      * Adds a customer to the queue

      *

      * @param time

      *            - time in the store

      * @param customer

      *            - customer

      */

      public void addToLine(int time, long customer) {

            // Add customer to the line

            queue.insert(customer);

           

            // Set time only if this is the first customer

            if (queue.size() == 1)

                  setTime(time);

      }

      /**

      * Returns the waiting time for a new customer. i.e. the time to process the

      * current customer plus the time to process the remaining customers (if

      * any).

      *

      * @param time

      *            - time in the store

      * @return - If line is empty returns 0, if line if full returns -1 else

      *         returns the waiting time for a new customer.

      */

      public int waitingTime(int time) {

            if (queue.isEmpty()) // Check if line is empty

                  return 0;

            else if (queue.isFull()) // Check if line is full

                  return -1;

            else {

                  // Find time elapsed after the current customer arrived at the

                  // checker

                  int timeElapsed = (time - this.startTime);

                  // Find the time remaining to process the current customer

                  int timeForCurrCustomer = this.processingTime - timeElapsed;

                  // If there are more than 1 customer, then to calculate the average

                  // waiting time for a new customer, we have to assume that the

                  // checker

                  // will require the same processing time for the remaining

                  // customers.

                  int timeForRemainingCustomer = ((queue.size() - 1) * this.processingTime);

                  // Return the total wait time

                  return timeForCurrCustomer + timeForRemainingCustomer;

            }

      }

      /**

      * Updates the checker as per the time.

      *

      * @param time

      *            - time in the store

      */

      public void updateLine(int time) {

            // Check if line is not empty

            if (!queue.isEmpty()) {

                  // Find time elapsed after the current customer arrived at the

                  // checker

                  int timeElapsed = (time - this.startTime);

                  // Check if the current customer is billed

                  if (timeElapsed == this.processingTime) {

                        // Remove the customer from the queue

                        queue.remove();

                        // Reset start time and processing time

                        startTime = -1;

                        processingTime = -1;

                        // If there is any other customer in the line, then set the

                        // startTime and processing time for that customer

                        if (!queue.isEmpty())

                              setTime(time);

                  }

            }

      }

      /**

      * Sets the start and processing time as per the store's time

      *

      * @param time

      *            - store time

      */

      private void setTime(int time) {

            startTime = time;

            processingTime = random.nextInt(10) + 1;

      }

}

/**

* This class simulates a store.

*/

public class Store {

      // The array to hold the customer who will be arriving at the checker

      private static long[] customer = { 10, 20, 30, 40, 50, 60, 70 };

      // Instance variables

      private int nCheckers;

      private Checker[] checker;

      private int time; // Time in minutes

      private int customerNum;

      /**

      * Constructor

      *

      * @param nCheckers

      *            - number of checkers in the store

      * @param maxLL

      *            - max line length

      */

      public Store(int nCheckers, int maxLL) {

            this.nCheckers = nCheckers;

            // Init checker array

            this.checker = new Checker[this.nCheckers];

            // Create each checker

            for (int i = 0; i < this.nCheckers; i++)

                  this.checker[i] = new Checker(maxLL);

            // Set start of the time/tick

            this.time = 0;

            // Customer number

            this.customerNum = 0;

      }

      /**

      * Displays all checkers at the store

      */

      public void display() {

            for (int i = 0; i < checker.length; i++) {

                  System.out.print("Checker " + (i + 1) + ": ");

                  checker[i].display();

            }

      }

      /**

      * Increments the time by 1.

      */

      public void masterTick() {

            time += 1;

            // After the time ticks, update all the checkers

            updateChecker();

      }

      /**

      * Updates all the checkers as per the time

      */

      private void updateChecker() {

            for (Checker c : checker)

                  c.updateLine(time);

      }

      /**

      * Simulates the entry of a new customer at one of the checkers.

      */

      public void newCustomer() {

            int minWaitTime = Integer.MAX_VALUE; // Minimum waiting time

            int checkerNum = -1; // The checker number where waiting time will be

                                                // minimum

            // Find the line where waiting time is minimum

            for (int i = 0; i < checker.length; i++) {

                  // Get waiting time at the checker

                  int waitTime = checker[i].waitingTime(time);

                  // If the wait time at checker[i] is less than minWaitTime

                  if (waitTime < minWaitTime) {

                        minWaitTime = waitTime;

                        checkerNum = i;

                  }

            }

            // If checkerNum is -1 that means all the lines are full and the

            // customer will have to wait

            // Check if a checker with minimum wait time is found

            if (checkerNum != -1) {

                  // Add customer to the line

                  checker[checkerNum].addToLine(time, customer[customerNum++]);

            }

      }

      /**

      * Checks whether there is any customer left

      *

      * @return - Returns true if there is a customer left, false otherwise

      */

      public boolean hasNextCustomer() {

            return (customerNum < customer.length);

      }

}

/**

* This class simulates a store.

*/

import java.io.IOException;

import java.util.Scanner;

public class SimApp {

      // Scanner to get user input

      private static Scanner in = new Scanner(System.in);

      /**

      * Gets a character from the user.

      *

      * @return - Returns the character if it is valid (s or t or e), else

      *         returns -1

      */

      private static int getChar() {

            String ans = in.nextLine().trim().toLowerCase();

            // Check if the correct character is entered

            if (ans.equals("s") || ans.equals("t") || ans.equals("e"))

                  return ans.charAt(0);

            else

                  return -1;

      }

      public static void main(String[] args) throws IOException {

            int nCheckers = 3; // number of checkers

            int maxLL = 12; // maximum line length

            Store theStore = new Store(nCheckers, maxLL);

//          while (true) {

            while (theStore.hasNextCustomer()) {

                  System.out.print("Enter first letter of ");

                  System.out.print("show, tick, enter: ");

                  int choice = getChar();

                  switch (choice) {

                  case 's':

                        theStore.display();

                        break;

                  case 't':

                        theStore.masterTick();

                        theStore.display();

                        break;

                  case 'e':

                        theStore.newCustomer();

                        theStore.display();

                        break;

                  default:

                        System.out.print("Invalid entry\n");

                  } // end switch

            } // end while

      } // end main()

}

SAMPLE OUTPUT:

Enter first letter of show, tick, enter: s Checker 1: Checker 2: Checker 3: Enter first letter of show, tick, enter: e Checke

Checker 1: 50 Checker 2: 20 Checker 3: 40

Please find below a table which traces the above output. You have to run the program in DEBUG mode in eclipse to get the processing time for each customer.

s e t e t t e e e t Action Time at store Checker 1 0 0 1 1 2 3 3 3 3 4 (Customer 10 has been billed and hence moved out of th

Thank you. please upvote.

Add a comment
Know the answer?
Add Answer to:
please explain all the steps. I need it ASAP. i will give u good ratings. Do...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Add a member method to the Queue class shown in attached code in Learning material/week6-7, and...

    Add a member method to the Queue class shown in attached code in Learning material/week6-7, and this added method will remove and return the second element of this queue. The headline of this function has been given below. public long removeSecond() { // your code here } class queue: class Queue { private int maxSize; private long[] queArray; private int front; private int rear; private int nItems;

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

  • Add a method called median() to the ArrayIns class in the insertSort.java program (Listing 3.3). This...

    Add a method called median() to the ArrayIns class in the insertSort.java program (Listing 3.3). This method should return the median value in the array. (Recall that in a group of numbers half are larger than the median and half are smaller.) Do it the easy way. LISTING 3.3 The insertSort.java Program // insertSort.java // demonstrates insertion sort // to run this program: C>java InsertSortApp //-------------------------------------------------------------- class ArrayIns { private long[] a; // ref to array a private int nElems;...

  • To the HighArray class in the highArray.java, add a method called getMax() that returns the value...

    To the HighArray class in the highArray.java, add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty. Add some code in main() to exercise this method. You can assume all the keys are positive numbers. // highArray.java class HighArray { private long[] a; private int nElems;    public HighArray(int max)    { a = new long[max];    nElems = 0; } public boolean find(long searchKey) { int...

  • HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE...

    HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the top element from Stack int topElement(); // get the top element void display(); // display Stack elements from top to bottom }; void Stack...

  • JAVA- Trace the recursive quick sort and partition methods in Lab6.java for this list of numbers:...

    JAVA- Trace the recursive quick sort and partition methods in Lab6.java for this list of numbers: 47 71 15 35 66 61 44 26 68 56 18 19 36 84 69 55 1. Find the value of pivot 2. Show the result after partitionIt() is called first time 3. Show the value of partition 4. Show the content of the array ///////////////////////////// Lab6.java class ArrayIns { private long[] theArray; // ref to array theArray private int nElems; // number of...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • add/ remove any methods to the program. please post new code and output Min Heap: public...

    add/ remove any methods to the program. please post new code and output Min Heap: public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT