【发布时间】:2013-01-30 16:24:51
【问题描述】:
我想创建一个程序,用户可以在其中输入项目,这些项目将存储在一个数组中。当用户对物品的数量感到满意时,如果他得到了每个物品,程序就会询问。
问题是我似乎无法创建一个大小未知的数组。我尝试使用这样的东西:String[] list = new string[]{}; 但是当程序运行到那里时,它会给出一个 IndexOutOfRangeException。
有什么办法可以做到吗?
这是完整的代码:
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> -
StackOverflow 上有大量的 C# 数组问题——你看过了吗?特别是stackoverflow.com/questions/599369/… ?