Sales Report

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Make a program that prints out a sales report for three employees.

We won't worry about input for now. You can use these hard-coded values:
Employee 1 = {1,7,6,8,8}
Employee 2 = {0,0,6,5,9}
Employee 3 = {3,2,4,8,2}

These values each represent one day of sales, in 100s of dollars.

Your sales report should print out the total sales of each employee as well as the total sales for each day.

 

More with Arrays

Wiki method01.jpg

Solution

First we need to set up our hard-coded values. So we can go over all of our values at once, we will store these numbers in a 2-dimensional array. Let's also store our sums in arrays.

 public class SalesReport
{
  public static void main(String[] args)
  {
    final int[][] SALES = { {1,7,6,8,8},
                            {0,0,6,5,9},
                            {3,2,4,8,2} };
    int[] employeeSales;
    int[] dailySales;
  }
} 

We can find the number of employees and the number of work days from our SALES array. This makes it easier to add new employees later or to change the amount of days each person works.

 public class SalesReport
{
  public static void main(String[] args)
  {
    final int[][] SALES = { {1,7,6,8,8},
                            {0,0,6,5,9},
                            {3,2,4,8,2} };
    int[] employeeSales;
    int[] dailySales;

    employeeSales = new int[ SALES.length ];
    dailySales = new int[ SALES[0].length ];
  }
} 

Now we need to iterate over SALES to add up our employee sales. This is similar to our sumArray code except we are doing it multiple times, once for each employee.

 public class SalesReport
{
  public static void main(String[] args)
  {
    final int[][] SALES = { {1,7,6,8,8},
                            {0,0,6,5,9},
                            {3,2,4,8,2} };
    int[] employeeSales;
    int[] dailySales;

    employeeSales = new int[ SALES.length ];
    dailySales = new int[ SALES[0].length ];

    for(int emp = 0;emp < SALES.length;emp++)
    {
      for(int day = 0;day < SALES[emp].length;day++)
      {

        employeeSales[emp] += SALES[emp][day];

      }
    }
  }
} 

We can use the same loop to sum the daily sales by moving using our counters as different indexes.

 public class SalesReport
{
  public static void main(String[] args)
  {
    final int[][] SALES = { {1,7,6,8,8},
                            {0,0,6,5,9},
                            {3,2,4,8,2} };
    int[] employeeSales;
    int[] dailySales;

    employeeSales = new int[ SALES.length ];
    dailySales = new int[ SALES[0].length ];

    for(int emp = 0;emp < SALES.length;emp++)
    {
      for(int day = 0;day < SALES[emp].length;day++)
      {

        employeeSales[emp] += SALES[emp][day];
        dailySales[day] += SALES[emp][day];

      }
    }
  }
} 

Now all that's left is to actually print out the report.

Code

Solution Code

Back to the Program-A-Day homepage