Learn-dsa..in 30 days!



























CC-12 : Implement a simple shopping car POC. The order of adding items to the shopping cart should be preserved.

Description:

Implement a simple shopping cart POC where the order of adding items to the car is preserved. Assume only 1 quantity of a particular item can be added to the cart.

Test cases and expected outputs:

Input Parameters Expected outputs
SetSimpleShoppingCart sCart=new SetSimpleShoppingCart();
sCart.addToCart("Nike Shoes Size 8 Quantity 1");
The shopping cart contents:
1 Nike Shoes Size 8 Quantity 1
sCart.addToCart("Nike TShirt Color TEAL Size M Quantity 1"); The shopping cart contents:
1 Nike Shoes Size 8 Quantity 1
2 Nike TShirt Color TEAL Size M Quantity 1
sCart.addToCart("Nike Deo Quantity 1"); The shopping cart contents:
1 Nike Shoes Size 8 Quantity 1
2 Nike TShirt Color TEAL Size M Quantity 1
3 Nike Deo Quantity 1
sCart.removeItem("Nike TShirt Color TEAL Size M Quantity 1"); The shopping cart contents:
1 Nike Shoes Size 8 Quantity 1
2 Nike Deo Quantity 1
sCart.addToCart("Nike TShirt Color BLUE Size M Quantity 1"); TThe shopping cart contents:
1 Nike Shoes Size 8 Quantity 1
2 Nike Deo Quantity 1
3 Nike TShirt Color BLUE Size M Quantity 1

Pseudocode:

Create a java class called SetSimpleShoppingCart.
In SetSimpleShoppingCart object initialize a member variable sCart of type LinkedHashSet. Note that a LinkedHashSet preserves the order in which elements are added to it.
Create a method addToCart() that takes an item as input:
In the method add item to sCart.
Create a method removeItem() that takes an item as input:
Remove item from sCart.
Create a method printCartContents() that iterates through sCart and prints the contents of the shopping cart. Since we have used a LinkedHashSet, the order in which items are added to cart are preserved while printing the shopping cart’s contents.

Code:

public class SetSimpleShoppingCart {
	
	LinkedHashSet<String> sCart=new LinkedHashSet<String>();
		
	public void addToCart(String item) {
		sCart.add(item);
	}
		


	public boolean removeItem(String item) {
		return sCart.remove(item);
	}


	public void printCartContents(){
		ArrayList aCart=new ArrayList(sCart);
		Iterator itr=aCart.iterator();
		System.out.print("\nThe shopping cart  contents: ");
		int itemCnt=1;
		while (itr.hasNext()) {
			System.out.print("\n" + itemCnt+ " "+itr.next()+ " ");
			itemCnt++;
		}	
		System.out.println("\n");
	}
}

Click here to download and run code and test cases !