1 public class Inventory {
2 // Transaction variables
13 public Inventory(int howmany) {
14 numitems = howmany;// howmany keeps track of the number of items
19 // Add item to a list of inventory
20 public synchronized int additem(String name, int quantity, int price){
21 ItemInfo newitem = new ItemInfo(quantity, price);
22 balance-=quantity*price;
24 // Get the item from hash
25 if (map.containsKey(name) == false) {
26 map.put(name, newitem);
28 ItemInfo i = (ItemInfo) map.get(name);
29 i.quantity += quantity;
36 // Buy item from a given list of inventory
37 public synchronized int buyitem(String name, int quantity){
38 if (map.containsKey(name) == false) {
39 // System.printString("Error - Item does not exist");
42 ItemInfo i = (ItemInfo) map.get(name);
43 if (i.quantity == 0) {
44 // System.printString("Error - Item unavailable");
47 if ((i.quantity-quantity) < 0 ) {
48 // System.printString("Error - Available qty is less: Cannot Buy\n");
51 i.quantity -= quantity;
53 balance+=quantity*i.price;
60 //Display the inventory list
61 public synchronized void inventory(Socket s){
62 HashMapIterator i = new HashMapIterator(map, 0);// Gets key from the hashmap= name of item
63 HashMapIterator j = new HashMapIterator(map, 1);//Gets the value from hashmap
64 int totalvalue=balance;
65 while (i.hasNext() == true) {
66 StringBuffer sb = new StringBuffer("");
68 String name = o.toString();
69 ItemInfo oo = (ItemInfo) j.next();
72 Integer q = new Integer(oo.quantity);
73 sb.append(q.toString());
75 Integer p = new Integer(oo.price);
76 sb.append(p.toString());
78 totalvalue+=oo.quantity*oo.price;
79 s.write(sb.toString().getBytes());
81 StringBuffer sb=new StringBuffer("");
82 sb.append("Total value: ");
83 sb.append((new Integer(totalvalue)).toString());
85 s.write(sb.toString().getBytes());