I have to do an exercise using arrays. The user must enter 3 inputs (each time, information about items) and the inputs will be inserted in the array. Then I must to display the array.
However, I am having a difficult time increasing the array's length without changing the information within it; and how can I allow the user to enter another set of input? This is what I have so far:
public string stockNum;
public string itemName;
public string price;
string[] items = new string[3];
public string [] addItem(string[] items)
{
System.Console.WriteLine("Please Sir Enter the stock number");
stockNum = Console.ReadLine();
items.SetValue(stockNum, 0);
System.Console.WriteLine("Please Sir Enter the price");
price = Console.ReadLine();
items.SetValue(price, 1);
System.Console.WriteLine("Please Sir Enter the item name");
itemName = Console.ReadLine();
items.SetValue(itemName, 2);
Array.Sort(items);
return items;
}
public void ShowItem()
{
addItem(items);
Console.WriteLine("The stock Number is " + items[0]);
Console.WriteLine("The Item name is " + items[2]);
Console.WriteLine("The price " + items[1]);
}
static void Main(string[] args)
{
DepartmentStore depart = new DepartmentStore();
string[] ar = new string[3];
// depart.addItem(ar);
depart.ShowItem();
}
So my question boils down to:
How can I allow the user to enter more than one batch of input? For example, the first time the user will enter the information about item ( socket number, price and name), but I need to allow the user enter more information about another item?
How can I display the socket num, price and name for each item in the array based on the assumption that I have more than one item in the array?
You can use
System.Collections.Generic.List<T>
which provides a resizable collection which also has a.ToArray()
method to return an ordinary array if you need it.If you have access to System.Linq then you can use the handy extension method Concat for IEnumerable objects such as arrays. This will allow you to extend an array:
Result:
1
2
3
4
Can you use ArrayList instead? It will resize as needed.
Use a list, and then convert to an array.
In fact, in this example, you should have a class or struct for StockInfo {stock number, price, item name}, then you should enter the data into a List. Finally, you could convert to StockInfo[] by using the ToArray method of the list.