问题描述
我想创建一个程序,用户可以在其中输入项目,这些项目将存储在数组中。当用户对项目数量没问题时,程序将询问是否获得了每个项目。
I want to create a program where users can input there items and those items will be stored in an array. When the user is okay with the amount of items, the program will ask for every item if he got it.
问题是我似乎无法创建一个数组大小未知。我试图使用类似这样的东西: String [] list = new string [] {};
但是,当程序运行到那里时,它会给出IndexOutOfRangeException。
The problem is i cant seem to create an array that is of unknown size. I tried to use something like this: String[] list = new string[]{};
But when the program goes there it gives an IndexOutOfRangeException.
有没有办法做到这一点?
Is there a way i can do this?
这是完整的代码:
bool groceryListCheck = true;
String[] list = new string[]{};
String item = null;
String yon = null;
int itemscount = 0;
int count = 0;
while (groceryListCheck)
{
Console.WriteLine("What item do you wanna go shop for?");
item = Console.ReadLine();
list[count] = item;
count++;
Console.WriteLine("Done?");
yon = Console.ReadLine();
if (yon == "y")
{
groceryListCheck = false;
itemscount = list.Count();
}
else
{
groceryListCheck = true;
}
}
for (int x = 0; x < itemscount; x++)
{
Console.WriteLine("Did you got the " + list[x] + "?");
Console.ReadKey();
}
推荐答案
使用,而不是数组
。
List<string> myList = new List<string>();
myList.Add("my list item");
收集所有项目后,可以使用 foreach
循环遍历集合中的所有项目。
After you have gathered all of the items, you can then use a foreach
loop to iterate through all of the items in the collection.
foreach(string listItem in myList)
{
Console.WriteLine(listItem);
}
这篇关于制作大小未知的数组C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!