@jlacar/

SalesReportWithTotals

Java

Based on this discussion: https://coderanch.com/t/705986/java/Create-object-works-array

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.Scanner;

/* Based on discussion here: 
 *
 * https://coderanch.com/t/705986/java/Create-object-works-array
 *
 */

class Main {
  public static void main(String[] args) {
    new SalesReport(testData()).display();
  }

  private static String testData() {
    return lineItem(1, 53)
        + lineItem(5, 10)
        + lineItem(3, 15)
        + lineItem(4, 25)
        + lineItem(2, 30)
        + lineItem(4, 15)
        + lineItem(5, 3)
        + lineItem(1, 130)
        + lineItem(3, 42)
        + lineItem(2, 17)
        + lineItem(1, 8)
        + lineItem(4, 29)
        + lineItem(0, 0);
  }

  private static String lineItem(int product, int quantity) {
    return String.format("%d %d%n", product, quantity);
  }
}

class SalesReport {
    private static final int END_OF_INPUT = 0;

    private final Scanner in;

    private int totalQuantity = 0;
    private double totalAmount = 0.0;

    SalesReport() {
      in = new Scanner(System.in);
    }

    SalesReport(String input) {
      in = new Scanner(input);
    }

    void display() {
       if (!in.hasNextInt()) {
         System.out.println("No data available.");
         return;
       }

       System.out.println("Sales Report");
       processLineItems();
       showTotals();
    }

    private void processLineItems() {
       int product = in.nextInt();
       while (product != END_OF_INPUT) {
         int quantity = in.nextInt();
         double lineAmount = saleAmount(product, quantity);
         addTotal(quantity, lineAmount);
         displayLineItem(product, quantity, lineAmount);

         product = in.nextInt();
       }
    }

    private void addTotal(int quantity, double amount) {
      totalQuantity += quantity;
      totalAmount += amount;
    }

    private void displayLineItem(int product, int quantity,
        double saleAmount) {

      System.out.printf("%d  %4d  %,10.2f%n", product, quantity, saleAmount);
    }

    private double saleAmount(int product, int quantity) {
      return priceFor(product) * quantity;
    }   

    private double priceFor(int product) {
      switch (product) {
        case 1: return 2.98; 
        case 2: return 4.50; 
        case 3: return 9.98; 
        case 4: return 4.49; 
        case 5: return 6.87; 
        default: return 0.0;
      }
    }

    private void showTotals() {
      System.out.printf("%nSummary%n");
      System.out.printf("Total items: %d%n", totalQuantity);
      System.out.printf("Total sales: %,.2f%n", totalAmount);
    }
}