[英]C# Index out of bounds
我正在尝试进行线性搜索,用户输入一组数字,然后他们输入一个随机数,程序会显示它是否在列表中。
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
Console.WriteLine("Enter number you want to find.");
int n1 = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i <= 10;)
{
if (list[i] == n1)
{
Console.WriteLine(n1 + " is in the list.");
found = true;
Console.ReadKey();
}
else i++;
}
if (found == false)
{
Console.WriteLine("Element not in this list.");
}
Console.ReadKey();
我很确定问题出在这段代码中。
int[] list = new int[10];
bool found = false;
for (int i = 0; i < 12;)
{
Console.WriteLine("Enter number to be stored.");
list[i] =Convert.ToInt16(Console.ReadLine());
i++;
}
一个 0 的数组,所以有 11 个元素空间,对吗? 所以当我运行它时,我 go 过去输入第 10 个数字,当我输入第 11 个数字时,它会中断并说
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
首先,我建议您阅读 C# 中的for
循环和 arrays。
其次,您不想在 for 循环中硬编码长度 - 让框架使用list.Length
为您完成。 您看到崩溃是因为您尝试为数组分配值,但数组中的索引不存在。
int[] list = new int[10];
bool found = false;
for (int i = 0; i < list.Length; i++)
{
// Do work with list[i]
}
当你说int[10];
你告诉它有10个条目。 它们从零开始计数,是的,但这仅意味着您的数组具有索引0, 1, 2, 3, 4, 5, 6, 7, 8, 9
。
您的循环在停止之前从i = 0
到i = 11
,因为它不再小于十二。 但是数组的索引最多可以是9
。
如果设置断点,您应该能够在调试器中查看数组内容。 这样,您也可以自己测试这些东西。
如果您的数组仅包含 10 个对象,则它应该是 i < 10 或 i <= 9。 10 个指数为 0-9。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.