[英]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.