0% found this document useful (0 votes)
18 views3 pages

Java Shopping Cart Implementation

The document defines classes for items, shopping carts, and fresh items. The Item class stores name, price, and quantity of an item. The Shoppingcart class can add items, count items, display items, get total quantity and total price. The FreshItem class extends Item to also store a best before date. A test class creates sample items, adds them to shopping carts, and displays totals.

Uploaded by

Aymen Douibi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Java Shopping Cart Implementation

The document defines classes for items, shopping carts, and fresh items. The Item class stores name, price, and quantity of an item. The Shoppingcart class can add items, count items, display items, get total quantity and total price. The FreshItem class extends Item to also store a best before date. A test class creates sample items, adds them to shopping carts, and displays totals.

Uploaded by

Aymen Douibi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

public class Item

{
private String name ;
private long price ;
private int quantity ;

public Item (String N,long P,int Q)


{
N= name ;
P= price ;
Q= quantity ;
}

Item() {
throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}
public String getname()
{
return name;
}
public long getprice()
{
return price;
}
public int getquantity ()
{
return quantity;
}

public class Shoppingcart


{
Item [] Shoppingcart = new Item [5] ;

int in =0 ;
public Shoppingcart() {}

public void addItem (Item it) {


if (in>=5)
{ [Link]("Shoppingcart is full "); }
else {
Shoppingcart [in]=it;
in++ ;}}
public int Itemcount()
{return in ;}
public void affichItem (){
for (int i=0;i<=4;i++)
{ [Link]((i+1)+ " name "+ Shoppingcart[i].getname()+" price "
+ Shoppingcart[i].getprice()+ " quantity "+ Shoppingcart[i].getquantity());}
}
public int Itemquantity ()
{ int quntityTotal=0;
for(int i=0;i<=4;i++)
{quntityTotal=quntityTotal+Shoppingcart[i].getquantity();}
return quntityTotal ;

public long totalPrice()


{ long TotalPrice=0;
for(int i=0;i<=4;i++)
{TotalPrice=TotalPrice+Shoppingcart[i].getprice();}
return TotalPrice;
}

}
public class FreshItem extends Item {
FreshItem [] cartitem = new FreshItem [5] ;
int in =0 ;
private String BestBeforeDate;

public FreshItem(String Name, long Price, int Quantity,String BestBeforeDate)


{
super(Name, Price, Quantity);
[Link]=BestBeforeDate;
}
FreshItem() {}
public String getBestBeforeDate() {
return BestBeforeDate;
}
public void setBestBeforeDate(String bestBeforeDate) {
BestBeforeDate = bestBeforeDate;}

void addFresh(Item fresh1) {


throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}
public void addFresh (FreshItem fit) {
if (in>=5)
{ [Link](" FreshItem is full "); }
else {
cartitem [in]= fit ;
in++ ;}}
public int FreshItemcount()
{return in ;}
public void affichFreshItem (){
for (int i=0;i<=4;i++)
{ [Link]((i+1)+ " name "+ cartitem[i].getname()+" price "
+ cartitem[i].getprice()+ " quantity "+ cartitem[i].getquantity());}
}
public int FreshItemquantity ()
{ int quntityTotal=0;
for(int i=0;i<=4;i++)
{quntityTotal=quntityTotal+ cartitem[i].getquantity();}
return quntityTotal ;}
}

public class test


{
public static void main(String[] args) {
Item item1 = new Item("water",200,1);
Item item2 = new Item("bread",500,7);
Item item3 = new Item("Milk",800,4);
Item item4 = new Item("coffee",400,3);
Item item5 = new Item("Salmon",700,5);

Shoppingcart cart1= new Shoppingcart();

[Link](item1);
[Link](item2);
[Link](item3);
[Link](item4);
[Link](item5);

[Link]();

Item fresh1 = new Item("water",200,1);


Item fresh2 = new Item("bread",500,7);
Item fresh3 = new Item("Milk",800,4);
Item fresh4 = new Item("coffee",400,3);
Item fresh5 = new Item("Salmon",700,5);

FreshItem cart2=new FreshItem();

[Link] (fresh1);
[Link] (fresh2);
[Link] (fresh3);
[Link] (fresh4);
[Link] (fresh5);

[Link]("le nombre total des articles est: "+


[Link]());
[Link]("la Quantite total des articles est: "+
[Link] ());
[Link]("le prix total de tous les articles est: "+
[Link]()+"Da");

}
}

Common questions

Powered by AI

Using fixed-size arrays within the Item and FreshItem classes limits the number of items that can be contained at any given time (maximum of five), potentially leading to scalability issues as the demands for more storage grow. This fixed limitation can prevent the dynamic addition of items, which is not scalable as the application requirements increase. In a scalable design, arrays would be replaced with dynamic data structures like lists, which allow flexible memory usage and growth by resizing automatically or using linked data structures to manage collections of indefinite sizes efficiently .

The Shoppingcart class reflects encapsulation principles by maintaining internal data (like the array of items and the current index) as private. The class provides public methods like addItem, Itemcount, and affichItem to interact with the shopping cart, thus controlling how the Shoppingcart's data is accessed and modified. This ensures that the underlying data structure is not directly manipulated from outside the class, preserving data integrity and abstraction .

The current design of the FreshItem class includes redundant methods like the addFresh method for non-FreshItem parameters and throws UnsupportedOperationException. To improve efficiency, these redundant or unused methods should be removed. Additionally, since FreshItem is a subclass of Item, it inherits all fields and methods; hence, the cartitem array could utilize the inherited fields and methods from Item without redefining them. It could also benefit from implementing interfaces that define the behaviors expected of cart items, promoting a more modular and adaptable design. These changes would streamline the class structure, reduce complexity, and enhance maintainability .

One potential issue is that the Shoppingcart array is fixed at a size of five, which can lead to a full cart scenario where no additional items can be added, as indicated by the message 'Shoppingcart is full'. Additionally, using a fixed-size array can lead to inefficient use of memory if not all slots are utilized. In a real-world scenario, these issues could be addressed by using a dynamic data structure such as an ArrayList, which automatically resizes as items are added. Furthermore, implementing capacity checks and dynamically resizing the cart based on needs could improve usability and performance .

Constructors in the given classes play a crucial role in initializing object states. The Item class constructor initializes an item's name, price, and quantity. However, a bug exists where parameters should be assigned to the object's fields, not vice versa, potentially leading to uninitialized object state. The FreshItem constructor extends initialization by adding a best-before date besides calling the superclass constructor to handle inherited attributes. Proper use of constructors ensures that objects begin with a valid, expected state, preventing runtime issues from uninitialized data. Addressing initialization errors by correcting assignments and consistently using constructors can enhance reliability and clarity in object handling .

The FreshItem class design can be leveraged for inventory management by utilizing its specific attributes such as the best-before date, indicating when items should be consumed or considered for restocking. Additional methods could be implemented to automate inventory checks, alerting managers of products approaching their expiration date. Inventory logic can incorporate algorithms that prioritize older stock and track usage trends, optimizing ordering cycles, and minimizing waste. By integrating these features, the FreshItem class could support comprehensive management of perishable goods, improving operational efficiency .

In the affichItem method, a potential data handling error could occur if there is an attempt to access an uninitialized or null item in the Shoppingcart array beyond the number of added items. Since the loop runs based on a fixed index from 0 to 4 without checking if the array elements are non-null, this could lead to a null pointer exception when accessing methods of uninitialized items. To prevent this, the method should iterate only up to the current value of 'in', which tracks successfully added items, thus ensuring that all accessed elements are valid .

The current method for calculating total price in Shoppingcart simply sums up the prices of each item without considering any discounts. In contrast, a strategy that includes discounts would need to apply a reduction factor to certain items or the total based on specific criteria (e.g., sales, loyalty programs). To accommodate discounts, the totalPrice method could be updated to take additional parameters representing discount rates or conditions, applying these discounts to qualifying items and adjusting the total price calculation accordingly. This could involve iterating over the cart's items and adjusting prices with discount factors before summing .

Overriding methods in the context of the FreshItem class enables it to exhibit different behaviors from the Item class while maintaining the same method signature, which is a key aspect of polymorphism. For instance, the FreshItem class overrides the addFresh method, allowing the class to handle instances of FreshItem specifically, including managing additional attributes like the 'Best Before Date'. This supports polymorphism by allowing the same method call to execute specific functions based on the object type, promoting flexibility and scalability within the program design .

To better verify the functionality of the Shoppingcart and FreshItem classes, the test class could be improved by incorporating assertions to check expected versus actual outcomes, instead of only printing results. Moreover, diverse test cases should be created to evaluate edge conditions, such as adding more than the allowed number of items and handling empty or null entries. Automated testing frameworks could be used to ensure repeatability and objectivity in tests, while mock objects might simulate external dependencies, enhancing the robustness and coverage of the tests .

You might also like