Sales Report
Back to the Program-A-Day homepage
ProblemMake a program that prints out a sales report for three employees. |
More with Arrays | |
---|---|---|
SolutionFirst 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 |