unity iventory. 1+1 = 4? - c#

Hi so im trying to create an inventory system
but very strangely when i try and add 1 to the item amount of an item. it adds 3
so if i add 1 item the next time i add one it will appear as 4 then 10 then 22 then 46 ect ect ect instead of just going 1,2,3,4
ive followed the variables im entering and at all stages they return the correct 1
its only after ive added it to the item amount it suddenly become the 4,10 ect`
if (Input.GetKeyUp(KeyCode.Space))
{
Item test = new Item();
test.ItemName = "testsss";
test.ItemID = 55;
test.Stackable = true;
test.ItemAmount = 1;
AddItem(test);
}
public void AddItem(Item item)
{
if (!isLocalPlayer) return;
if (InventoryCurrentWeight + item.ItemWeight < InventoryMaxWeight)
{
if (item.Stackable == true)
{
checkIfItemExists(item);
InvGui();
}
else
{
addItemAtEmptySlot(item);
InvGui();
}
}
else
{
Debug.Log("Too Much Weight");
}
}
public void checkIfItemExists(Item item)
{
if (!isLocalPlayer) return;
for (int i = 0; i < inventory.Count; i++)
{
if (inventory[i].ItemID == item.ItemID)
{
Debug.Log(item.ItemAmount);
Debug.Log("Before" +inventory[i].ItemAmount);
inventory[i].ItemAmount = inventory[i].ItemAmount + item.ItemAmount;
//CaclutateWeight();
Debug.Log("After" + inventory[i].ItemAmount);
break;
}
else if (i == inventory.Count - 1)
{
addItemAtEmptySlot(item);
}
}
}
and this is my item class that holds the data `
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item
{
public string ItemName;
public string ItemDescription;
public float ItemWeight;
public int ItemID;
public int ItemAmount;
public ItemType itemType;
public string Sprite;
public bool Stackable;
public enum ItemType
{
Coin,
Weapon,
Armour,
craftingMat,
StatItem
}
public Item(string name,string desc, float weight, int id, int amount, ItemType type,bool stackable)
{
ItemName = name;
ItemDescription = desc;
ItemWeight = weight;
ItemID = id;
ItemAmount = amount;
itemType = type;
Stackable = stackable;
}
public Item()
{
}
}`
`

Related

Using keyword "value" in set accessor C#

I'm trying to use the keyword value in the set accessor and as long as the user entered value is greater than 0, I want to set it to the variable Quantity.
I can not seem to find what it is I am doing wrong. I keep getting a traceback error to for this Quantity = value;. Hoping someone can see what I don't. Thanks.
using System;
namespace Invoice
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("How many parts would you like to " +
"enter into the system: ");
int newParts = int.Parse(Console.ReadLine());
Invoice[] invoice = new Invoice[newParts];
for (int i = 0; i < newParts; i++)
{
invoice[i] = new Invoice();
Console.WriteLine("Enter the part number: ");
invoice[i].PartNumber = Console.ReadLine();
Console.WriteLine("Enter description of item: ");
invoice[i].PartDescription = Console.ReadLine();
Console.WriteLine("Enter the quantity: ");
invoice[i].Quantity = int.Parse(Console.ReadLine());
Console.WriteLine("Enter in the price of the item: ");
invoice[i].PricePerItem = decimal.Parse(Console.ReadLine());
}
for (int i = 0; i < newParts; i++)
{
invoice[i].DisplayOrder();
}
}
}
}
using System;
namespace Invoice
{
public class Invoice
{
public string PartNumber { get; set; }
public string PartDescription { get; set; }
public int Quantity
{
get { return Quantity; }
set
{
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
}
}
public decimal PricePerItem
{
get
{
return PricePerItem;
}
set
{
if(value >= 0.0m)
{
PricePerItem = value;
}
if (value <= 0.0m)
{
PricePerItem = PricePerItem;
}
}
}
public Invoice(String PartNumber, String PartDescription, int Quantity, decimal PricePerItem)
{
this.PartNumber = PartNumber;
this.PartDescription = PartDescription;
this.Quantity = Quantity;
this.PricePerItem = PricePerItem;
}
public Invoice()
{
}
public decimal GetInvoiceAmount(int numberOfItems, decimal priceOfItem)
{
return numberOfItems * priceOfItem;
}
public void DisplayOrder()
{
decimal total = GetInvoiceAmount(Quantity, PricePerItem);
// Display Receipt
Console.Write("\nOrder Receipt: ");
Console.WriteLine($"\nPart Number: {PartNumber}");
Console.WriteLine($"Unit Price: {PricePerItem:C}");
Console.WriteLine($"Quantity: {Quantity}");
Console.WriteLine($"Part Description: {PartDescription}");
Console.WriteLine($"Total price: {total:C}");
}
}
}
This makes no sense:
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
Why would you set a property to itself? That can't achieve anything useful. You say that you want to set the property if and only if the assigned value is greater than zero, so why would you be checking value for anything but being greater than zero?
if (value > 0)
{
Quantity = value;
}
That's it, that's all.
That said, you also ought to be throwing an ArgumentOutOfRangeException if the value is not valid, rather than just silently not setting the property. The logical way to do that would be like so:
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
Quantity = value;
Now the property value will only be set if an exception is not thrown.
I also just realised that you have no backing field for this property, so that's wrong. The whole thing should look like this:
private int quantity;
public int Quantity
{
get { return quantity; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
quantity = value;
}
}
The error is because in your set {} you are invoking the same setter recursively.
private int quantity;
public int Quantity
{
get { return this.quantity; }
set
{
if (value >= 0)
{
this.quantity= value;
}
}
}
private decimal pricePerItem;
public decimal PricePerItem
{
get
{
return this.pricePerItem;
}
set
{
if(value >= 0.0m)
{
this.pricePerItem= value;
}
}
}

C# Compare two list and return value

I have a problem. I try compare two list currentItemsInColl and bPList. Inside bPList i have other list RequiredItems and now is what I need.
I want compare currentItemsInColl and RequiredItems and return bPList.craftingBlueprint.
I try Compare but I dont know how use it :/
using Devdog.InventoryPro;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CraftingAutoUpdate : MonoBehaviour {
public ItemCollectionBase itemCollection;
public ItemCollectionBase rewardCollection;
public CraftingCategory craftingCategory;
[Header("Blue Print List")]
public List<BlueprintList> bPList = new List<BlueprintList>();
public List<CurrentItemInCollList> currentItemsInColl = new List<CurrentItemInCollList>();
private CraftingBlueprint readyBlueprint;
public void OnShow()
{
GetBluePrint();
InvokeRepeating("StartUpdate",0f,0.05f);
}
public void OnHide()
{
CancelInvoke("StartUpdate");
}
private void StartUpdate()
{
UpdateDirectory();
UpdateFindMatchItems();
UpdateCraftResults();
}
private void GetBluePrint()
{
bPList.Clear();
foreach (var b in craftingCategory.blueprints)
{
if (b != null)
{
var rI = b.requiredItems;
var listReqItems = new List<RequiredItem>();
foreach (var e in rI)
{
listReqItems.Add(new RequiredItem(e.item.ID, e.amount));
}
bPList.Add(new BlueprintList(b.name, b, listReqItems));
}
}
}
private void UpdateDirectory()
{
currentItemsInColl.Clear();
foreach(var item in itemCollection)
{
if (item.item != null)
{
var cT = item.item.ID;
if (currentItemsInColl.Find(u =>u.itemID == cT) == null)
{
var itemCount = itemCollection.GetItemCount(item.item.ID);
currentItemsInColl.Add(new CurrentItemInCollList(item.item.ID, itemCount));
}
}
}
}
In this methode I try find same items in collections:
private void UpdateFindMatchItems()
{
readyBlueprint = null;
bool matchFailed = false;
int requiredItemCount = 0;
int currentItemsInCollCount = currentItemsInColl.Count;
foreach(var bp in bPList)
{
requiredItemCount = bp.RequiredItems.Count;
foreach(var rI in bp.RequiredItems)
{
if(CompareLists(currentItemsInColl, bp.RequiredItems))
{
print("aa");
}
print(currentItemsInCollCount);
}
}
private void UpdateCraftResults()
{
rewardCollection.Clear();
if (readyBlueprint != null)
{
foreach (var items in readyBlueprint.resultItems)
{
rewardCollection.AddItem(items.item,null,true,false);
}
}
}
I try somthing like this but is wont work with this lists:
public static bool CompareLists<T>(List<T> aListA, List<T> aListB)
{
if (aListA == null || aListB == null || aListA.Count != aListB.Count)
return false;
if (aListA.Count == 0)
return true;
Dictionary<T,T> lookUp = new Dictionary<T,T>();
// create index for the first list
for (int i = 0; i < aListA.Count; i++)
{
uint count = 0;
if (!lookUp.TryGetValue(aListA[i], out count))
{
lookUp.Add(aListA[i], 1);
continue;
}
lookUp[aListA[i]] = count + 1;
}
for (int i = 0; i < aListB.Count; i++)
{
uint count = 0;
if (!lookUp.TryGetValue(aListB[i], out count))
{
// early exit as the current value in B doesn't exist in the lookUp (and not in ListA)
return false;
}
count--;
if (count <= 0)
lookUp.Remove(aListB[i]);
else
lookUp[aListB[i]] = count;
}
// if there are remaining elements in the lookUp, that means ListA contains elements that do not exist in ListB
return lookUp.Count == 0;
}
}
And this is my lists:
/* LISTS */
[Serializable]
public class CurrentItemInCollList
{
public uint itemID;
public uint itemAmount;
public CurrentItemInCollList(uint newitemID, uint newItemAmount)
{
itemID = newitemID;
itemAmount = newItemAmount;
}
}
[Serializable]
public class BlueprintList
{
public string bluePrintName;
public CraftingBlueprint craftingBlueprint;
public List<RequiredItem> RequiredItems = new List<RequiredItem>();
public BlueprintList(string newBluePrintName, CraftingBlueprint newcraftingBlueprint, List<RequiredItem> list)
{
bluePrintName = newBluePrintName;
craftingBlueprint = newcraftingBlueprint;
RequiredItems = list;
}
}
[Serializable]
public class RequiredItem
{
public uint itemID;
public uint itemAmount;
public RequiredItem( uint newitemID, uint newItemAmount)
{
itemID = newitemID;
itemAmount = newItemAmount;
}
}
I forgot.. CurrentItemInCollList.itemAmount can be >= RequiredItems.itemAmount
Dictionary use hash values to compare objects.
The stored classes must implement public override int GetHashCode(){}
Use Linq - here is a small console example:
class Program
{
static void Main(string[] args)
{
//Required list
List<Order> currentItemsInColl = new List<Order>();
currentItemsInColl.Add(new Order() { Name = "bike1", Id = "01" });
currentItemsInColl.Add(new Order() { Name = "bike4", Id = "04" });
//List of all items
List<BPP> bPList = new List<BPP>();
bPList.Add(new BPP() { BikeName = "bike1", Idzzz = "01" });
bPList.Add(new BPP() { BikeName = "bike2", Idzzz = "02" });
bPList.Add(new BPP() { BikeName = "bike3", Idzzz = "03" });
bPList.Add(new BPP() { BikeName = "bike4", Idzzz = "04" });
bPList.Add(new BPP() { BikeName = "bike5", Idzzz = "05" });
//Blueprint List
List<BPP> Blueprint = new List<BPP>();
//get all items into the Blueprint list
foreach (Order i in currentItemsInColl)
{
List<BPP> tmp = bPList.FindAll(x => x.Idzzz.Contains(i.Id));
//here you add them all to a list
foreach (BPP item in tmp)
{
Blueprint.Add(item);
}
}
Console.ReadLine();
}
}
public class Order
{
public string Id { get; set; }
public string Name { get; set; }
}
public class BPP
{
public string Idzzz { get; set; }
public string BikeName { get; set; }
}
Sidenote: i am comparing the ID's in each of the lists! Hope it helps.

Reading a txt file, split string then write to txt file

I have a text file call groceries. That contain text similar to the following:
regular,cereal,4.00,1;
fresh,rump steak,11.99,0.8;
The code below is trying to read the text file, split the string and then write to a text file called invoice.
The invoice text file should read read line in the groceries file, list whether it is a "fresh" or "regular" grocery item. If fresh GST is not applied if regular GST is applied. Calculate the cost on weight for fresh and quantity for regular and then display a total cost of items listed.
Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines ("Groceries.txt");
File.WriteAllLines("Invoice.txt", invoices.ToArray());
List<string> invoices = new List<string>();
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "fresh";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "regular";
grocery.Price = 50;
grocery.Quantity = 2;
double price = price.Calculate();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
invoices.Add(counter + "," + grocery + price+Quantity+"," + DateTime.Now.Date);
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
try something like that
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines("Groceries.txt");
List<string> invoices = new List<string>();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
var list = grocery2.Split(',');
if (list[0].Equals("fresh"))
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = list[1];
freshGrocery.Price = double.Parse(list[2]);
freshGrocery.Weight = double.Parse(list[3].Replace(";", ""));
invoices.Add(counter + "," + freshGrocery.Name + "," + freshGrocery.Price + "," + freshGrocery.Weight + "," + DateTime.Now.Date);
}
else if (list[0].Equals("regular"))
{
Grocery grocery = new Grocery();
grocery.Name = list[1];
grocery.Price = double.Parse(list[2]);
grocery.Quantity = int.Parse(list[3].Replace(";", ""));
double price = grocery.Calculate();
invoices.Add(counter + "," + grocery.Name + "," + price + "," + grocery.Quantity + "," + DateTime.Now.Date);
}
}
File.WriteAllLines("Invoice.txt", invoices.ToArray());
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
}

Separate items by dictionary or list

I'm developing a game server for a game client. The game's character has an inventory, like any other game. The inventory has 4 tabs:
Equipment, Potions, Extra, Cash
Currently, the CharacterItems class is a List<Item>, where each Item object contains a Slot property which indicates the position of the item inside the window (the window is 4 by 4).
I don't really like this approach as it doesn't really indicate where each item is located, where with a dictionary I can have keys for each tab and then organize the item. However, I also need to index the items with a slot. So how can I use this approach with a dictionary? Wouldn't I need two dictionaries like so? Dictionary<InventoryTab, Dicitionary<int, Item>>, where InventoryTab is a certain tab and the keyed collection is indexed by the item's slot? Seems too cluttered, perhaps there is a better appraoch for this?
Also, the character also has wearable equipment on it. So that means I have to create another definition in the dictionary for equipped tab, which kinda ruins the logic.
Here's a test for the apparoach I mentioned before:
using System;
using System.Collections.Generic;
using System.Linq;
namespace InventoryTest
{
class Program
{
static void Main(string[] args)
{
var inventory = new Inventory();
while (true)
{
var mapleId = new Random().Next(1000000, 5999999);
short str = 0;
short dex = 0;
short intt = 0;
short luk = 0;
if (mapleId >= 1000000 && mapleId <= 1999999)
{
str = (short)new Random().Next(0, 5);
dex = (short)new Random().Next(0, 5);
intt = (short)new Random().Next(0, 5);
luk = (short)new Random().Next(0, 5);
}
var item = new Item()
{
MapleId = mapleId,
Str = str,
Dex = dex,
Int = intt,
Luk = luk
};
inventory.Add(item);
Console.ReadLine();
}
}
}
class Item
{
public int MapleId { get; set; }
public short Str { get; set; }
public short Dex { get; set; }
public short Int { get; set; }
public short Luk { get; set; }
public Tab Tab
{
get
{
return (Tab)(this.MapleId / 1000000);
}
}
}
enum Tab : byte
{
Equip = 1,
Use,
Setup,
Etc,
Cash
}
class Inventory : Dictionary<Tab, Dictionary<sbyte, Item>>
{
public Inventory()
: base()
{
foreach (var tab in Enum.GetValues(typeof(Tab)).Cast<Tab>())
{
base.Add(tab, new Dictionary<sbyte, Item>(96));
}
}
public void Add(Item item)
{
var nextFreeSlot = this.GetNextFreeSlot(item.Tab);
this[item.Tab].Add(nextFreeSlot, item);
Console.WriteLine("Added new item to {0} tab. Info:", item.Tab);
Console.WriteLine("Slot: {0}", nextFreeSlot);
Console.WriteLine("MapleId: {0}", item.MapleId);
if (item.Str > 0)
{
Console.WriteLine("Str: {0}", item.Str);
}
if (item.Dex > 0)
{
Console.WriteLine("Dex: {0}", item.Dex);
}
if (item.Int > 0)
{
Console.WriteLine("Int: {0}", item.Int);
}
if (item.Luk > 0)
{
Console.WriteLine("Luk: {0}", item.Luk);
}
}
private sbyte GetNextFreeSlot(Tab tab)
{
sbyte slot = 0;
foreach (var item in this[tab])
{
if (item.Key == slot)
{
slot += 1;
}
else
{
break;
}
}
return slot;
}
}
}

Delete function for simple inventory

I have a simple inventory application which is a program which you can add, view and delete the product. Currently I had already finished the add function and view function but left only the delete function which I am unsure of. ( Main program case 3)
class Inventory
{
Product []items;
int maxSize;
int size;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
size = 0;
items = new Product[maxSize];
}
public bool AddProduct(Product in_Product)
{
if(getSize()<maxSize)
{
items[size] = in_Product;
size++;
return true;
}
else
{
return false;
}
}
public int getSize()
{
return size;
}
public Product getProduct(int index)
{
return items[index];
}
}
}
here is my product class:
class Product
{
private string name;
private int itemNumber;
private int unitsInStock;
private double price;
private double value;
public Product()
{
}
public Product(string in_name, int in_itemNumber, int in_unitsInStock, double in_price)
{
name = in_name;
itemNumber = in_itemNumber;
unitsInStock = in_unitsInStock;
price = in_price;
}
public double getValueOfInventory()
{
value = unitsInStock * price;
return this.value;
}
public int getItemNumber()
{
return this.itemNumber;
}
public string getName()
{
return this.name;
}
public int getUnitsInStock()
{
return this.unitsInStock;
}
public double getPrice()
{
return this.price;
}
public void setItemNumber(int in_itemNumber)
{
itemNumber = in_itemNumber;
}
public void setName(string in_name)
{
name = in_name;
}
public void setUnitsInStock(int in_unitsInStock)
{
unitsInStock = in_unitsInStock;
}
public void setPrice(double in_price)
{
price = in_price;
}
}
}
Here is my main program:
class Program
{
static void Main(string[] args)
{
Inventory myInventory = new Inventory(100);
Product myProduct = new Product();
myProduct.setItemNumber(1000);
myProduct.setName("Pen");
myProduct.setPrice(1.25);
myProduct.setUnitsInStock(50);
myInventory.AddProduct(myProduct);
Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
myInventory.AddProduct(myProduct1);
Product tempProduct;
int x = 0;
do
{
Console.WriteLine("1.Add product");
Console.WriteLine("2.View product");
Console.WriteLine("3.Delete product");
Console.WriteLine("4.Exit the Application");
Console.WriteLine("------------------");
x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 1:
Console.Write("Item number\t\t:");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
string b=Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
double c=Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
int d=Convert.ToInt32(Console.ReadLine());
Product myProduct2 = new Product(b,a,d,c);
myInventory.AddProduct(myProduct2);
// Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
// myInventory.AddProduct(myProduct1);
/*Console.Write("Item number\t\t:");
ItemNo = Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
Name = Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
Price = Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
UnitsInStocks = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("------------------");*/
break;
case 2:
for (int i = 0; i < myInventory.getSize(); i++)
{
tempProduct = myInventory.getProduct(i);
Console.WriteLine("Item number\t\t:" + tempProduct.getItemNumber());
Console.WriteLine("Name\t\t\t:" + tempProduct.getName());
Console.WriteLine("Price\t\t\t:" + tempProduct.getPrice());
Console.WriteLine("Units in stocks\t\t:" + tempProduct.getUnitsInStock());
Console.WriteLine("------------------");
}
break;
case 3:
int j;
Console.WriteLine("Please enter the item id for the items that you want to delete");
j = Convert.ToInt32(Console.ReadLine());
if (j == a)
{
break;
case 4:
Environment.Exit(0);
break;
default:
break;
}
}
while (x != 4);
}
}
}
In my main program, i left case 3 undone as that is the delete function part,
How can I accomplish this?
This is the simple way. Replace your array with a List of products:
class Inventory
{
List<Product> items;
int maxSize;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
items = new List<Product>();
}
public bool AddProduct(Product in_Product)
{
if(items.Count < maxSize)
{
items.Add(in_Product);
return true;
}
else
{
return false;
}
}
public Product getProduct(int index)
{
return items[index];
}
public void removeProduct(int index)
{
items.removeAt(index);
}
}
In your switch call removeProduct method to delete the product at position that you pass.

Categories