Thursday, June 2, 2016

Design Interview Question - Design a Grocery Store.

Problem: Design a Grocery Store.

Answer:

For this what we need is:

  • A customer class
  • A store Class
  • A GroceryItem of various sorts
  • A cashier


/**
 * @author Abhinaw.Tripathi
 *
 */

class Customer
{
public GroceryItem[] myshoppinBasket =new GroceryItem[20];
Random random=new Random();
double myMoney=100.00;



public void shop(GroceryStore store)
{
selectGroceries(store);
checkOut(store);
}

public void checkOut(GroceryStore store)
{
Cashier cashier=store.getCasiCashier();
 double total=cashier.getBill(myshoppinBasket);
 myMoney=myMoney - total;
 cashier.pay(total);

}

public void selectGroceries(GroceryStore store)
{

int itemsInmybasket=0;
for(int i=0;i<store.KINDS_OF_ITEM;i++)
{
for(int j=0;j<3;j++)
{
if(random.nextInt(2) == 1)
{
myshoppinBasket[itemsInmybasket]=store.item[i];
store.itemCount[i] =store.itemCount[i]-1;
itemsInmybasket=itemsInmybasket + 1;
}
}
}
}

}

class Cashier
{
GroceryStore myStore;
public void takePosition(GroceryStore store)
{
myStore=store;
}


public double getBill(GroceryItem[] item)
{
double total=0;
int itemNUmber=0;
while(item[itemNUmber]!=null)
{
total=total +item[itemNUmber].price ;
System.out.println(item[itemNUmber].name + " " + item[itemNUmber].price);
itemNUmber= itemNUmber+1;
}
System.out.println("Total" + total);
return total;
}

public void pay(double amount)
{
myStore.money=myStore.money + amount;
}

}

class GroceryItem
{
 public String name;
 public double price;
 public GroceryItem(String name,double price) {

this.name=name;
this.price=price;
}

}

class Store
{
  Cashier myCashier;

  public Cashier getCashier()
  {
 return myCashier;
  }

}


public class GroceryStore
{
Cashier myCashier;
public int KINDS_OF_ITEM=4;
public GroceryItem[] item=new GroceryItem[KINDS_OF_ITEM];
public int[] itemCount=new int[KINDS_OF_ITEM];
double money =1000.00;


public GroceryStore()
{
item[0]=new GroceryItem("milk",2.12);
item[1]=new GroceryItem("butter",2.502);
item[0]=new GroceryItem("eggs",1.12);

for(int i=0;i<KINDS_OF_ITEM;i++)
{
itemCount[i]=50;
}
}

public void hire(Cashier cashier)
{
myCashier=cashier;
cashier.takePosition(this);
}

public Cashier getCasiCashier()
{
return myCashier;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

GroceryStore store=new GroceryStore();
Cashier cashier=new Cashier();
Customer customer=new Customer();
customer.shop(store);
store.hire(cashier);

}


}

No comments: