arraylist

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maniacCow
    New Member
    • Aug 2010
    • 24

    arraylist

    I'm a beginner in programming world...
    Currently, I coding a simple food ordering simulation.
    It is something like this:-

    Qty:1 Foodname:Fried rice
    Qty:1 Foodname:Noodle
    Qty:1 Foodname:Fried rice

    Just wanna ask, is there anyway to make the order list become:-

    Qty:2 Foodname:Fried rice
    Qty:1 Foodname:Noodle

    Which mean everything I key in a new food it will trace the list. If the food is exist, then the quantity will increase by 1.
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    I would suggest, using a Dictionary.
    In a Dictionary you can store keys (unique) and values.

    E.g. you have a Dictionary where the Key is the foodname (type string) and the value is quantity (type int)

    Code:
    Dictionary<string, int> _foodOrders = new Dictionary<string, int>();
    After you've declared and defined it, you can start to add values (_foodOrders.Ad d(key, value)) to your dictionary.
    But if you add a key more than once, you'll get an Exception, because it's not allowed to store two same keys.

    So you've got to check out, if the key is already existing, and if it is, you only increase it's quantity.

    There is a dictionary's method ContainsKey() to check if the key is already existing. You can access the dictionary's values with _foodOrders[key] like _foodOrders["Noodle"].

    Comment

    • maniacCow
      New Member
      • Aug 2010
      • 24

      #3
      Is it possible that it create another same food name if the quantity limit is reach.

      Eg. Limit is set to 3 units only.

      Qty:3 Foodname:Fried rice
      Qty:1 Foodname:Noodle

      If user enter Fried rice again, the order list will become:-

      Qty:3 Foodname:Fried rice
      Qty:1 Foodname:Noodle
      Qty:1 Foodname:Fried rice

      Comment

      • Christian Binder
        Recognized Expert New Member
        • Jan 2008
        • 218

        #4
        You won't be able to do this with a Dictionary.
        You have to use another data-structure than Dictionary.

        Maybe take a List of FoodOrders.
        So you create a class FoodOrder which consists of a string-variable for the foodname and an integer for the count of orders.

        Every time you have to insert a food order, you go through you whole list and search for a FoodOrder-item which has the same name as the food you want to insert and which has available space for another order, e.g. the qty is less than three.
        Give it a try :-)

        Comment

        Working...