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

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

Utilitiy functions

File size: 1.9 KB
RevLine 
[253]1package onetomany.bargainingchipsgame;
[233]2
3/**
[265]4 * Stack contains a number of {@link Chip} objects of the same color and price.
[271]5 * A stack=(chip, quantity, price).
[233]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.
[271]7 * Aggregation of a stack with the empty stack is itself.
[233]8 *
[271]9 * Immutable.
[233]10 */
[239]11public class Stack
12{
[271]13 private final Chip chip;
14 private final double price;
15 private final int quantity;
[233]16
[271]17 public Stack(Chip c, double p, int q)
[233]18 {
[265]19 chip = c;
[271]20 price = p;
[265]21 quantity = q;
[233]22 }
[266]23
[271]24 public Stack(String c, double p, int q)
[266]25 {
[271]26 this(new Chip(c), p, q);
[266]27 }
[271]28
[233]29 /**
30 * @return the chip
31 */
32 public Chip getChip() {
33 return chip;
34 }
35
36 /**
37 * @return the quantity
38 */
[239]39 public int getQuantity()
40 {
[233]41 return quantity;
42 }
43
[282]44 public double getUnitPrice()
[233]45 {
[271]46 return price;
[233]47 }
[282]48
49 public double getTotalPrice()
50 {
51 return price * quantity;
52 }
[233]53
[243]54 public String getColor()
55 {
56 return chip.getColor();
57 }
58
[257]59 public boolean hasSameColorAs(Stack s)
60 {
[271]61 return getChip().equals(s.getChip());
[257]62 }
63
[233]64 public Stack aggregateWith(Stack s)
65 {
[271]66 if (s!=null && s.hasSameColorAs(this))
67 {
68 int q = quantity + s.getQuantity();
[282]69 double p = (getUnitPrice()*quantity+s.getUnitPrice()*s.getQuantity())/q;
[271]70 return new Stack(getChip(), p, q);
[265]71 } else
72 throw new IllegalStateException("\n\n[Warning] StackClass::aggregateWith(Stack). Different colors! Aggregating "+s+" into "+this+" is not possible.");
73 }
[233]74
75 @Override
76 public String toString()
77 {
[282]78 return getQuantity()+"x"+getChip()+"($" + getUnitPrice() + ")";
[233]79 }
[266]80
81 public static void main(String[] args)
82 {
83 Stack s = new Stack("Red", 9.0, 3);
84 Stack t = new Stack ("Red", 4.0, 2);
85 System.out.println(s + " + " + t + " = " + s.aggregateWith(t));
86 System.out.println(t + " + " + s + " = " + t.aggregateWith(s));
87 }
[233]88}
Note: See TracBrowser for help on using the repository browser.