Solved

Using an Addition function in a shopping cart class

Posted on 2011-03-20
13
247 Views
Last Modified: 2012-05-11
I am trying to build a shopping cart class and inside that class I am trying to add an addition function.  For each item I add into the shopping cart, I want to increment the total price of the items.  I'm kind of at a loss but I am thinking it requires a foreach statement.  Here is what I have so far, please help:

 double AddShoppingCartItems(ShoppingCartItem SRItem)
        {
            ShoppingCartItem cartitem;
            cartitem = new ShoppingCartItem();

            double itemprice;
            double totalitemprice;
           
            cartitem.ItemId = SRItem.ItemId;
            cartitem.ItemDescription = SRItem.ItemDescription;
            cartitem.ItemPrice = SRItem.ItemPrice;

            itemprice = cartitem.ItemPrice;



           
        }        
0
Comment
Question by:VBBRett
  • 8
  • 5
13 Comments
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178059
OK, there is a number of options. And I believe different implementations have different approaches.

Option 1. In your ShoppingCart class you have a variable, say, totalCost. Each time you add an item to a cart, you increase this variable. And you should not forget to decrease it if you remove an item. And set to 0 if you clear the cart.

Personally, I don't like this.

2. I'd have a separate function that iterates through all the items and calculates total cost when it's needed.
Say, your CartItem has a property ItemPrice and a property ItemQuantity. In this case the pseudo code would be something like:

double TotaCartlCost(){
   double result = 0.0;
   for each CartItem in entire cart
   {
           result = result + CartItem.ItemPrice * CartItem.ItemQuantity;

    }

   return result;

}


I believe it will be fast enough and less error prone.

0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178073
Anyway, in your Cart class you need to have a list (or any other collection) of Cart items, so that you may add items and remove from this collection.

If you decide with the first approach all you need is to add code to your method like:


// class level variable:
double mTotalCartPrice;
double AddShoppingCartItems(ShoppingCartItem SRItem)
        {
            ShoppingCartItem cartitem;
            cartitem = new ShoppingCartItem();

            double itemprice;
            double totalitemprice;
            
            cartitem.ItemId = SRItem.ItemId;
            cartitem.ItemDescription = SRItem.ItemDescription;
            cartitem.ItemPrice = SRItem.ItemPrice;

// I believe this line has no sense. Where you get cartitem.ItemPrice from?
//You just created this object...

            itemprice = cartitem.ItemPrice;

            mTotalCartPrice = mTotalCartPrice + cartitem.ItemPrice;

            
        }

Open in new window

0
 

Author Comment

by:VBBRett
ID: 35178074
Sorry for my silly question, but would you be able to provide me with an example?  I am not familiar with the for each statement.  Thanks!
0
 

Author Comment

by:VBBRett
ID: 35178106
cartitem.itemprice is a variable where I thought I would hold the price of an item that was funnelled through my function through the (ShoppingCartItem SRItem) from the AddShoppingCartItems function.  The shoppingcartitem class has the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for ShoppingCartItem
/// </summary>
/// 
namespace MarketingEmail
{
    public class ShoppingCartItem
    {
        private int itemid;
        private string itemdescription;
        private double itemprice;

        public int ItemId
        {
            get
            {
                return itemid;
            }
            set
            {
                if (value < 0)
                {
                    throw new Exception("Invalid ItemId");
                }
                itemid = value;
            }
        }

        public string ItemDescription
        {
            get
            {
                return itemdescription;
            }
            set
            {
                if (value.Length < 1)
                {
                    throw new Exception("Invalid Description");
                }
                itemdescription = value;
            }
        }

        public double ItemPrice
        {
            get
            {
                return itemprice;
            }
            set
            {
                if (value < 0)
                {
                    throw new Exception("Invalid Price");
                }
                itemprice = value;
            }
        }

    }
}

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178130
What is in this case?
 
0
 

Author Comment

by:VBBRett
ID: 35178144
I guess I am looking to do a foreach statement to add up all the shopping cart items.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178147
Implementation for foreach loop:


public double  cartTotalPrice()
        {
            double result = 0.0;

            foreach (ShoppingCartItem item in MyShoppingCart.Items)
            {
                result = result + CartItem.ItemPrice * CartItem.ItemQuantity;
            }
            return result;

        }

Open in new window

0
 

Author Comment

by:VBBRett
ID: 35178155
Is MyShoppingCart.Items supposed to be in my shoppingcart class?
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178159
OK, in your implementation your CartItem has no Quantity property. So, if you want to add 10 items to your cart, you just call AddItem 10 times? Or how you track a number of same items?

Also, your  AddShoppingCartItems(ShoppingCartItem SRItem) method is a bit strange. Honestly, I can't understand what you are trying to do?

See, your parameter is a ShoppingCartItem. Inside the method you create another ShoppingCartItem and copy values from one to another. Where you store all items that were added before?

Is that a homework you are trying to do?
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178168
"Is MyShoppingCart.Items supposed to be in my shoppingcart class?"

I'd say 'yes'. You need some storage for your cart items. And some List or Dictionary would be a good place. In your shoppingcart class you create a collection and put all items there.
0
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 35178175
Have a look at some examples (heaps on Internet):

http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35178177
have to go...
0
 

Author Comment

by:VBBRett
ID: 35178190
To be honest, I am still pretty new at this and that is developing things out of Object Oriented Programming objects as opposed to Procedural code.  So, excuse me if I sound a bit lost.  What I am trying to do is to get an incrementer in my code so that I don't have to keep adding on my C# page so that everything just works as opposed to program again.  So, I am trying to program some kind of collection of items so that the total cost keeps getting added as I add more to a shopping cart and as I remove things from the shopping cart, things get removed.  So, let's say I have widgets, here is an example of what I would like to do.

I click a button and 1 widget that costs $10 gets added to the cart.

so I have the following in my cart:

1 widget cost: $10

total cost: $10

Now, if I add another widget, here is what would happen.

2 widgets cost: $20

total cost: $20

If I remove a widget, then the following would happen:

1 widget cost: $10

total cost: $10.

Now, if I add something else besides a widget, here is what would happen in the shopping cart:

1 widget: $10

1 ball: $5

total cost: $15

And so on and so forth.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now