source: src/main/java/onetomany/bargainingchipsgame/Stack.java@ 266

Last change on this file since 266 was 266, checked in by Tim Baarslag, 5 years ago

Tested Stack:

3 x (Red, $9.0) + 2 x (Red, $4.0) = 5 x (Red, $7.0)
2 x (Red, $4.0) + 3 x (Red, $9.0) = 5 x (Red, $7.0)

File size: 1.9 KB
Line 
1package onetomany.bargainingchipsgame;
2
3/**
4 * Stack contains a number of {@link Chip} objects of the same color and price.
5 * A stack=(chip, quantity).
6 * Aggregation of a two stacks of the same colors, creates another stack with the total quantity but its chip in a new price equal to weighted average of the both unit prices.
7 * Aggregation of a stack with the empty stack is itself.
8 *
9 * @author Faria Nassiri-Mofakham
10 *
11 */
12public class Stack
13{
14 private Chip chip;
15 private int quantity;
16
17 public Stack(Chip c, int q)
18 {
19 chip = c;
20 quantity = q;
21 }
22
23 public Stack(String color, double price, int qty)
24 {
25 chip = new Chip(color, price);
26 quantity = qty;
27 }
28
29 /**
30 * @return the chip
31 */
32 public Chip getChip() {
33 return chip;
34 }
35
36 /**
37 * @return the quantity
38 */
39 public int getQuantity()
40 {
41 return quantity;
42 }
43
44 public double getPrice()
45 {
46 return chip.getPrice()*quantity;
47 }
48
49 public String getColor()
50 {
51 return chip.getColor();
52 }
53
54 public boolean hasSameColorAs(Stack s)
55 {
56 return getColor().equals(s.getColor());
57 }
58
59 public Stack aggregateWith(Stack s)
60 {
61 if (s!=null && chip.hasSameColorAs(s)) {
62 String color = getChip().getColor();
63 double p = (getChip().getPrice()*quantity+s.getChip().getPrice()*s.getQuantity())/(quantity+s.getQuantity());
64 return new Stack(new Chip(color, p), quantity + s.getQuantity());
65 } else
66 throw new IllegalStateException("\n\n[Warning] StackClass::aggregateWith(Stack). Different colors! Aggregating "+s+" into "+this+" is not possible.");
67 }
68
69 @Override
70 public String toString()
71 {
72 return getQuantity()+" x "+getChip();
73 }
74
75 public static void main(String[] args)
76 {
77 Stack s = new Stack("Red", 9.0, 3);
78 Stack t = new Stack ("Red", 4.0, 2);
79 System.out.println(s + " + " + t + " = " + s.aggregateWith(t));
80 System.out.println(t + " + " + s + " = " + t.aggregateWith(s));
81 }
82}
Note: See TracBrowser for help on using the repository browser.