| Counter.java |
1 package example;
2
3 /**
4 * Simple example class to show how to use ComTest.
5 * Counter is a class that counts sum, min and max
6 * of the items added. Only maxN item is taken acount.
7 *
8 * @author vesal
9 *
10 * @example
11 * <pre name="testJAVA">
12 * private Counter cnt;
13 *
14 * /.** *./
15 * \@Before public void doInit() {
16 * cnt = new Counter(3);
17 * }
18 *
19 * /.** *./
20 * \@After public void doAfter() {
21 * System.out.println("After: " + cnt.getCount());
22 * }
23 * </pre>
24 */
25 public class Counter {
26 private int count = 0;
27 private int max = 0;
28 private int min = 0;
29 private int sum = 0;
30 private final int maxN;
31
32 /**
33 * Init counter with max N items
34 * @param maxN
35 */
36 public Counter(int maxN) {
37 this.maxN = maxN;
38 }
39
40 /**
41 * Adds i to current counter if not allready too many added.
42 * @param i value to add
43 * @example
44 * <pre name="testCounterAdd">
45 * #THROWS IndexOutOfBoundsException,Exception
46 * // Test by ordinary sentences
47 * // Counter cnt = new Counter(3);
48 * cnt.getCount() === 0; cnt.getSum() === 0;
49 * cnt.add(1); cnt.getCount() === 1; cnt.getSum() === 1;
50 * cnt.add(2); cnt.getCount() === 2; cnt.getSum() === 3;
51 * </pre>
52 *
53 * @example
54 * <pre name="testCounterAddTable">
55 * // test by table
56 * Counter cnt = new Counter(3);
57 * cnt.add($add); cnt.getCount() === $count; cnt.getSum() === $sum;
58 * cnt.getMax() === $max; cnt.getMin() === $min;
59 *
60 * ----------------------------------------------
61 * $add | $count | $sum | $max | $min
62 * ----------------------------------------------
63 * --- | 0 | 0 | 0 | 0 // after creation
64 * 1 | 1 | 1 | 1 | 1
65 * 2 | 2 | 1+2 | 2 | 1
66 * 3 | 3 | 1+2+3 | 3 | 1
67 * 4 | 3 | 6 | 3 | 1 // MaxN exceeded
68 * ==============================================
69 * 5 | 1 | 5 | 5 | 5
70 * 2 | 2 | 5+2 | 5 | 2
71 * 3 | 3 | 5+2+3 | 5 | 2
72 * ==============================================
73 * -1 | 1 | -1 | -1 | -1
74 * 2 | 2 | -1+2 | 2 | -1
75 * 9 | 3 | -1+2+9 | 9 | -1
76 *
77 * </pre>
78 */
79 public void add(int i) {
80 if ( count >= maxN ) return;
81 sum += i;
82 count++;
83 if ( count == 1 ) min = max = i;
84 if ( max < i ) max = i;
85 if ( min > i ) min = i;
86 }
87
88 /** @return count of items */
89 public int getCount() { return count; }
90
91 /** @return max item */
92 public int getMax() { return max; }
93
94 /** @return min item */
95 public int getMin() { return min; }
96
97 /** @return Sum of items */
98 public int getSum() { return sum; }
99
100 /** @return Avg of items */
101 public double getAvg() { if ( getCount() > 0 ) return getSum()/getCount(); else return 0; }
102
103
104 }
105