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

This is what I have so far, if you do make changes please bold them so I can wor

ID: 3869023 • Letter: T

Question

This is what I have so far, if you do make changes please bold them so I can work through it.

----------------------------

Main Controller:

package pcproblem;

import java.io.Console;

import java.time.LocalDate;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Queue;

import java.util.Scanner;

import java.util.concurrent.ThreadLocalRandom;

public class ProducerConsumer implements Runnable{

   private final Producer[] producers;

   private final Consumer[] consumers;

   //int p = console.nextInt();

   public ProducerConsumer(int p, int c) {

       producers= new Producer[p]; //makes 5 of those

       consumers= new Consumer[c]; //makes 2 of these

   }

   public void run() {

       //run method; main thread

       // start p producers

       int k; //reusing because local index

       int limit = 10000;

       for(int j=0; j<limit; j++)

       {

           k=j%producers.length; //10000 / producers.length

           try {

               producers[k].produce();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

       // start c consumers

       //each different consumer is assigned a different item from the queue

       for(int j=0; j<limit; j++)

       {

           k=j%consumers.length;

           try {

               consumers[k].consume();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

   }

   public static void main(String[] args) {

  

       int p = 0;

       int c = 0;

  

       try {

           System.out.println("Enter p and c:");

          

           //implementing scanner method because cant do java producerconsumer from command line says cant find main method

           //p = Integer.parseInt(args[0]);

           //1c = Integer.parseInt(args[1]);

           Scanner in = new Scanner(System.in);

           p = in.nextInt();

           c = in.nextInt();

          

          

       } catch (Exception e) {

           System.out.println("Error");

           return;

       }

      

      

       final long startTime = System.currentTimeMillis();

       System.out.println("Timer is started");

       // in read me the command from the user will be ex. ProducerConsumer(5,2)  

       //System.out.print("Please enter p and c in format ProducerConsumer(p,c): ");  

       ProducerConsumer pc = new ProducerConsumer(p,c);

       Queue<Item> sharedList = new ArrayDeque<Item>(); //created a sharable between a consumer and producer

       //creating the threads for the methods

       //takes the shared list as an object from the constructor

       Thread thread1 = new Thread(new Producer(sharedList, p));

       Thread thread2 = new Thread(new Consumer(sharedList, p));

       //Activate the threads

       thread1.start();

       thread2.start();

  

  

       final long endTime = System.currentTimeMillis();

       //Total time for simulation (from begin to end)

       System.out.println("Total execution time: " + (endTime - startTime) );

   }

}

——————————————

Producer:

package pcproblem;

import java.time.LocalDate;

import java.util.Date;

import java.util.Queue;

import java.util.concurrent.ThreadLocalRandom;

import java.util.Random;

class Producer implements Runnable{

   //this will be using a shared resource

   Queue<Item> sharedQueue = null;

   //set the final size to 10000

   final int MAX_SIZE = 10000;

   private int p;

   //System.out.println(storeId);

   // private ArrayList<Item> items = new ArrayList<Item>();

   public Producer(Queue<Item> sharedList, int p) {

       super();

       this.sharedQueue = sharedList;

       this.p = p;

   }

  

   // Use to generate a sale from this store

   private Item GenerateRandomItem() {

       //Generate Store Id

Random rand = new Random();

int storeId = rand.nextInt(this.p) + 1;

System.out.println("Store Id:" + storeId);

  

      

       //SALES DATE GENERATOR

       LocalDate startDate = LocalDate.of(2016, 1, 1); //start date

       long start = startDate.toEpochDay();

       //this.p

       LocalDate endDate = LocalDate.of(2016, 12, 31); //end date

       long end = endDate.toEpochDay();

      

       long mydate = ThreadLocalRandom.current().longs(start, end).findAny().getAsLong();

       System.out.println("Date:" + LocalDate.ofEpochDay(mydate)); // random date between the range

       //RANDOMLY GENERATE REGISTER NUMBER

       int registerNum = ThreadLocalRandom.current().nextInt(1, 6 + 1);

       System.out.println("Register Number:" + registerNum);

       //SALE AMOUNT

       float saleAmount = (float)ThreadLocalRandom.current().nextDouble(0.50, 1000.99);

       System.out.println("Sale Amount:" + saleAmount); //implement %.2f to cut down the float point

      

       return new Item(new Date(mydate), storeId, registerNum, saleAmount);

   }

   @Override

   public void run() {

       // call the produce method in the run so it can keep iterating it

       while(true){

           try {

               produce();

           } catch (InterruptedException e) {

              

               e.printStackTrace();

           }

       }

   }

   //produce method

   public void produce() throws InterruptedException{

       //for(int i=0; i < numToProduce; i++){

           //generate an item

           Item newItem = GenerateRandomItem();

           //return newItem;

      

   //   }

      

       // must wait until there's room in the queue

       synchronized (sharedQueue){

          

           while(sharedQueue.size() >= MAX_SIZE){

               //once the object has been produced it needs to wait for consumer to consume it

               System.out.println("Semaphore is employed;producer is waiting:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

           System.out.println("Producting Sales Record :" + newItem);

           sharedQueue.add(newItem);

           //Thread.sleep(500);

           //Thread.sleep((int)(Math.random() * 10) * 100);

      

          

           sharedQueue.notifyAll(); //notify consumer who is waiting while it doesnt have anything

          

          

       }

   }

}

—————————

Consumer:

package pcproblem;

import java.util.Queue;

//consumer is statistics collector

class Consumer implements Runnable{

   //this will be using a shared resource

   //List<Integer> sharedList = null;

   Queue<Item> sharedQueue = null;

   //set the final size to 10000

   final int MAX_SIZE = 10000;

  

   final ConsumerStatistics localstats;

   public ConsumerStatistics getLocalStats() {

       return localstats;

   }

   public Consumer(Queue<Item> sharedList, int p) {

       super();

       this.sharedQueue = sharedList;

       this.localstats = new ConsumerStatistics(p);

   }

   @Override

   public void run() {

       // call the produce method in the run so it can keep iterating it

       while(true){

           try {

               consume();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

   }

   //consume method

   public void consume() throws InterruptedException{

       synchronized (sharedQueue){

           while(sharedQueue.isEmpty()){

               //once the object has been consumed it needs to wait for producer

               System.out.println("Semaphore is employed;waiting on producer:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

       }

       //Add element to the list while it's not full

      

       synchronized (sharedQueue){

          

           while(sharedQueue.size() >= MAX_SIZE){

               //once the object has been produced it needs to wait for consumer to consume it

               //System.out.println("Semaphore is employed;producer is waiting:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

          

           //Item i = sharedQueue.remove();

           Item i = sharedQueue.poll();

          

           // If the queue is empty

           if (i == null){

               Thread.sleep((int)(Math.random() * 10) * 100);

           }

           else {

               //System.out.println("Consuming Sales Record :" + i);

           }

           sharedQueue.notifyAll(); //notify producer who is waiting while it doesnt have anything

       }

   }

   }

——————

Item:

package pcproblem;

import java.util.*;

public class Item {

  

     

      // Item class

      private Date salesdate;

      private int storeid;

      private int register;

      private float saleamount;

      // Item’s constructor

      Item(Date salesdate, int storeid, int register,float saleamount ) {

      // items = 0;

      this.salesdate = salesdate;

      this.storeid = storeid;

      this.register = register;

      this.saleamount = saleamount;

      }

       public Date getSalesdate() {

           return salesdate;

       }

       public int getStoreid() {

           return storeid;

       }

       public int getRegister() {

           return register;

       }

       public float getSaleamount() {

           return saleamount;

       }

      

       public String toString(){

           return storeid +"0"+ register;

       }

  

  

   }

—————

Consumer Statistics:

package pcproblem;

import java.io.Console;

import java.util.*;

public class ConsumerStatistics {

       final double totalStoreSales[];

  

       private static double monthlySales[] = new double[12]; //12 month per producer

      private double totalsales;

  

      private int simulationtime;

  

      double sum = 0.0;

      ConsumerStatistics(int producerCount) {

  

      totalStoreSales = new double[producerCount];

     

      System.out.println("Number of Stores:" + producerCount); //value of p

      System.out.println("Total Sales for Each Store:" + Arrays.toString(totalStoreSales));

  

      for(int i=0; i< producerCount; i++){

             double a= totalStoreSales[i];

             System.out.println("Number of Stores:" + a); //value of a

         }

  

      System.out.println("Agregate Sales:" + GetTotalSales());

      System.out.println("Sales for all:" + sum);

  

      //perMonthSale =0;

         //for(int perMonthSale=0; perMonthSale<producerCount; perMonthSale++){

             // perMonthSale.getSalesdate();

          

         //}

      

  

      }

  

  

      public void UpdateStatistics(Item i) {

         totalStoreSales[i.getStoreid()-1] += i.getSaleamount();

      

      }

  

      public void CalculateMontlySales(){

  

         //i.getSalesdate();

      

           

           for ( int currentMonth = 0; currentMonth < monthlySales.length; currentMonth++)

           { monthlySales[currentMonth] =

                   GetTotalSales();}

      

      }

  

      public double GetTotalSales(){

      

         for (double s_sum : totalStoreSales) {

             sum += s_sum;

         }

      

         return sum;

      

      }

  

}

  

I need help with my statistics.java class. The program is implemented correctly and works as expected. This class is a program feature and should be able to take care of the following: Display totalStoreSales where it shows sales sum for each individual store which I did my best to implement - - It should show store sales by month How much all stores together made - How long the program took to execute

Explanation / Answer

package pcproblem;

import java.io.Console;

import java.time.LocalDate;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Queue;

import java.util.Scanner;

import java.util.concurrent.ThreadLocalRandom;

public class ProducerConsumer implements Runnable{

   private final Producer[] producers;

   private final Consumer[] consumers;

   //int p = console.nextInt();

   public ProducerConsumer(int p, int c) {

       producers= new Producer[p]; //makes 5 of those

       consumers= new Consumer[c]; //makes 2 of these

   }

   public void run() {

       //run method; main thread

       // start p producers

       int k; //reusing because local index

       int limit = 10000;

       for(int j=0; j<limit; j++)

       {

           k=j%producers.length; //10000 / producers.length

           try {

               producers[k].produce();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

       // start c consumers

       //each different consumer is assigned a different item from the queue

       for(int j=0; j<limit; j++)

       {

           k=j%consumers.length;

           try {

               consumers[k].consume();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

   }

   public static void main(String[] args) {

  

       int p = 0;

       int c = 0;

  

       try {

           System.out.println("Enter p and c:");

          

           //implementing scanner method because cant do java producerconsumer from command line says cant find main method

           //p = Integer.parseInt(args[0]);

           //1c = Integer.parseInt(args[1]);

           Scanner in = new Scanner(System.in);

           p = in.nextInt();

           c = in.nextInt();

          

          

       } catch (Exception e) {

           System.out.println("Error");

           return;

       }

      

      

       final long startTime = System.currentTimeMillis();

       System.out.println("Timer is started");

       // in read me the command from the user will be ex. ProducerConsumer(5,2)  

       //System.out.print("Please enter p and c in format ProducerConsumer(p,c): ");  

       ProducerConsumer pc = new ProducerConsumer(p,c);

       Queue<Item> sharedList = new ArrayDeque<Item>(); //created a sharable between a consumer and producer

       //creating the threads for the methods

       //takes the shared list as an object from the constructor

       Thread thread1 = new Thread(new Producer(sharedList, p));

       Thread thread2 = new Thread(new Consumer(sharedList, p));

       //Activate the threads

       thread1.start();

       thread2.start();

  

  

       final long endTime = System.currentTimeMillis();

       //Total time for simulation (from begin to end)

       System.out.println("Total execution time: " + (endTime - startTime) );

   }

}

——————————————

Producer:

package pcproblem;

import java.time.LocalDate;

import java.util.Date;

import java.util.Queue;

import java.util.concurrent.ThreadLocalRandom;

import java.util.Random;

class Producer implements Runnable{

   //this will be using a shared resource

   Queue<Item> sharedQueue = null;

   //set the final size to 10000

   final int MAX_SIZE = 10000;

   private int p;

   //System.out.println(storeId);

   // private ArrayList<Item> items = new ArrayList<Item>();

   public Producer(Queue<Item> sharedList, int p) {

       super();

       this.sharedQueue = sharedList;

       this.p = p;

   }

  

   // Use to generate a sale from this store

   private Item GenerateRandomItem() {

       //Generate Store Id

Random rand = new Random();

int storeId = rand.nextInt(this.p) + 1;

System.out.println("Store Id:" + storeId);

  

      

       //SALES DATE GENERATOR

       LocalDate startDate = LocalDate.of(2016, 1, 1); //start date

       long start = startDate.toEpochDay();

       //this.p

       LocalDate endDate = LocalDate.of(2016, 12, 31); //end date

       long end = endDate.toEpochDay();

      

       long mydate = ThreadLocalRandom.current().longs(start, end).findAny().getAsLong();

       System.out.println("Date:" + LocalDate.ofEpochDay(mydate)); // random date between the range

       //RANDOMLY GENERATE REGISTER NUMBER

       int registerNum = ThreadLocalRandom.current().nextInt(1, 6 + 1);

       System.out.println("Register Number:" + registerNum);

       //SALE AMOUNT

       float saleAmount = (float)ThreadLocalRandom.current().nextDouble(0.50, 1000.99);

       System.out.println("Sale Amount:" + saleAmount); //implement %.2f to cut down the float point

      

       return new Item(new Date(mydate), storeId, registerNum, saleAmount);

   }

   @Override

   public void run() {

       // call the produce method in the run so it can keep iterating it

       while(true){

           try {

               produce();

           } catch (InterruptedException e) {

              

               e.printStackTrace();

           }

       }

   }

   //produce method

   public void produce() throws InterruptedException{

       //for(int i=0; i < numToProduce; i++){

           //generate an item

           Item newItem = GenerateRandomItem();

           //return newItem;

      

   //   }

      

       // must wait until there's room in the queue

       synchronized (sharedQueue){

          

           while(sharedQueue.size() >= MAX_SIZE){

               //once the object has been produced it needs to wait for consumer to consume it

               System.out.println("Semaphore is employed;producer is waiting:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

           System.out.println("Producting Sales Record :" + newItem);

           sharedQueue.add(newItem);

           //Thread.sleep(500);

           //Thread.sleep((int)(Math.random() * 10) * 100);

      

          

           sharedQueue.notifyAll(); //notify consumer who is waiting while it doesnt have anything

          

          

       }

   }

}

—————————

Consumer:

package pcproblem;

import java.util.Queue;

//consumer is statistics collector

class Consumer implements Runnable{

   //this will be using a shared resource

   //List<Integer> sharedList = null;

   Queue<Item> sharedQueue = null;

   //set the final size to 10000

   final int MAX_SIZE = 10000;

  

   final ConsumerStatistics localstats;

   public ConsumerStatistics getLocalStats() {

       return localstats;

   }

   public Consumer(Queue<Item> sharedList, int p) {

       super();

       this.sharedQueue = sharedList;

       this.localstats = new ConsumerStatistics(p);

   }

   @Override

   public void run() {

       // call the produce method in the run so it can keep iterating it

       while(true){

           try {

               consume();

           } catch (InterruptedException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

       }

   }

   //consume method

   public void consume() throws InterruptedException{

       synchronized (sharedQueue){

           while(sharedQueue.isEmpty()){

               //once the object has been consumed it needs to wait for producer

               System.out.println("Semaphore is employed;waiting on producer:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

       }

       //Add element to the list while it's not full

      

       synchronized (sharedQueue){

          

           while(sharedQueue.size() >= MAX_SIZE){

               //once the object has been produced it needs to wait for consumer to consume it

               //System.out.println("Semaphore is employed;producer is waiting:");

               sharedQueue.wait(); //SEMAPHORE EMPLOYED

           }

          

           //Item i = sharedQueue.remove();

           Item i = sharedQueue.poll();

          

           // If the queue is empty

           if (i == null){

               Thread.sleep((int)(Math.random() * 10) * 100);

           }

           else {

               //System.out.println("Consuming Sales Record :" + i);

           }

           sharedQueue.notifyAll(); //notify producer who is waiting while it doesnt have anything

       }

   }

   }

——————

Item:

package pcproblem;

import java.util.*;

public class Item {

  

     

      // Item class

      private Date salesdate;

      private int storeid;

      private int register;

      private float saleamount;

      // Item’s constructor

      Item(Date salesdate, int storeid, int register,float saleamount ) {

      // items = 0;

      this.salesdate = salesdate;

      this.storeid = storeid;

      this.register = register;

      this.saleamount = saleamount;

      }

       public Date getSalesdate() {

           return salesdate;

       }

       public int getStoreid() {

           return storeid;

       }

       public int getRegister() {

           return register;

       }

       public float getSaleamount() {

           return saleamount;

       }

      

       public String toString(){

           return storeid +"0"+ register;

       }

  

  

   }

—————

Consumer Statistics:

package pcproblem;

import java.io.Console;

import java.util.*;

public class ConsumerStatistics {

       final double totalStoreSales[];

  

       private static double monthlySales[] = new double[12]; //12 month per producer

      private double totalsales;

  

      private int simulationtime;

  

      double sum = 0.0;

      ConsumerStatistics(int producerCount) {

  

      totalStoreSales = new double[producerCount];

     

      System.out.println("Number of Stores:" + producerCount); //value of p

      System.out.println("Total Sales for Each Store:" + Arrays.toString(totalStoreSales));

  

      for(int i=0; i< producerCount; i++){

             double a= totalStoreSales[i];

             System.out.println("Number of Stores:" + a); //value of a

         }

  

      System.out.println("Agregate Sales:" + GetTotalSales());

      System.out.println("Sales for all:" + sum);

  

      //perMonthSale =0;

         //for(int perMonthSale=0; perMonthSale<producerCount; perMonthSale++){

             // perMonthSale.getSalesdate();

          

         //}

      

  

      }

  

  

      public void UpdateStatistics(Item i) {

         totalStoreSales[i.getStoreid()-1] += i.getSaleamount();

      

      }

  

      public void CalculateMontlySales(){

  

         //i.getSalesdate();

      

           

           for ( int currentMonth = 0; currentMonth < monthlySales.length; currentMonth++)

           { monthlySales[currentMonth] =

                   GetTotalSales();}

      

      }

  

      public double GetTotalSales(){

      

         for (double s_sum : totalStoreSales) {

             sum += s_sum;

         }

      

         return sum;

      

      }

  

}

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