可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
In .NET (C#), an array isn't resizable. It's not like in JavaScript or PHP were an array is made very flexible and can be extend with arbitrary elements.
Per definition an default static array has a fix size, so you can reference an element within by using the index. ( http://en.wikipedia.org/wiki/Array_data_structure#Array_resizing )
But there you can read about dynamic array. In C# it will be the System.Collections.ArrayList-Object. ( http://en.wikipedia.org/wiki/Dynamic_array )
So what you need is either the ArrayList-Definition or a normal list or generic list. (System.Collections.Generic.List)
string[] items = new string[3] { "input1", "input2", "input3" };
string[] moreItems = new string[10] { "input4", "input5" };
// array to list
List<string> itemsList = items.ToList<string>();
itemsList.Add("newItem");
// or merge an other array to the list
itemsList.AddRange(moreItems);
// list to array
string[] newArray = itemsList.ToArray();
回答2:
Starting with .NET Framework 3.5, for one-dimensional arrays you can use Array.Resize<T>
method:
int[] myArray = { 1, 2, 3 };
Array.Resize(ref myArray, 5);
MSDN link is here.
回答3:
I think you may be going about the problem wrong...
Consider that the three items (stock number, price, and name) are part of a larger object. For now we can just call it item
. We want to store a number of item
s in a list or array. Consider using an object-oriented approach like this:
class Widget
{
public int StockNum;
public int Price;
public string Name;
Widget(stockNum, price, name)
{
this.StockNum= stockNum;
this.Price = price;
this.Name = name;
}
}
Now, you can can instantiate a list of these objects:
List<Widget> items = new List<Widget>();
And add items to them:
for (int i = 0; i < 5; i++)
{
//Get input from user
System.Console.WriteLine("Please Sir Enter the stock number");
stockNum= Convert.ToInt32(Console.ReadLine()); //This isn't very safe...
System.Console.WriteLine("Please Sir Enter the price");
price = Convert.ToInt32(Console.ReadLine()); //This isn't very safe...
System.Console.WriteLine("Please Sir Enter the item name");
name = Console.ReadLine();
//Then add it to a new object
Widget item = new Widget(stockNum, price, name);
//And add this item to a list
items.Add(item);
}
回答4:
Assuming your assignment requires you to use Arrays and not other collection classes, then you will have to do things the hard way.
Arrays are immutable, that is you cannot change them after they have been created. You can change the contents, but not the size of the array. If you need to grow or shrink the array, you will have to create a new array with the new number of items, then copy the items you want from the old array to the new array.
For instance, suppose you want to take an array and only copy the even elements.
int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] a2 = new int[a.Length / 2];
int counter = 0;
for (int i = 0; i < a.Length; i = i + 2)
{
a2[counter++] = a[i];
}
Then, you could always assign a2 back to a
a = a2;
回答5:
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.
回答6:
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.
回答7:
Can you use ArrayList instead? It will resize as needed.
回答8:
I've had the same problem but could not change the type and had to stuck with Array since I was extending an existent API class. Here's a simple template method that extends an existent array:
public static T[] ExtendArray<T> ( T[] array , uint index) where T:new()
{
List<T> list = new List<T>();
list.AddRange(array);
while (list.Count < index) {
list.Add(new T());
}
return list.ToArray();
}
Please note that the above also initializes the elements with the default constructor.
回答9:
You could work around the 'problem' of not being able to resize arrays by using an array that is as big as the biggest array you expect to have. Note that this is considered hacking, not structured programming!
回答10:
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:
int[] result = new int[] { 1, 2 };
int[] extend = new int[] { 3, 4 };
result = result.Concat(extend).ToArray();
foreach (int i in result)
{
Console.WriteLine(i.ToString());
}
Result:
1
2
3
4