[英]compile error:index out of range
i want to write merge sort algorithm,when i debug the program and give numbers to it,it goves index out of range error,whats the problem of my code?thanks in advance. 我想编写合并排序算法,当我调试程序并给它编号时,它使索引超出范围错误,我的代码有什么问题?请先感谢。
private void button3_Click(object sender, EventArgs e)
{
string[] source = textBox1.Text.Split(',');
string[] source1 = textBox3.Text.Split(',');
int[] nums2 = new int[source1.Length + source.Length];
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int[] nums1 = new int[source1.Length];
for (int j = 0; j < source1.Length; j++)
{
nums1[j] = Convert.ToInt32(source1[j]);
}
int x=0;
int y=0;
int z=0;
while (x <=nums.Length && y <= nums1.Length)
{
if (nums[x] <= nums1[y])///it gives out of range on this line
{
nums2[z] = nums[x];
x++;
}
else
{
nums2[z] = nums1[y];
y++;
}
z++;
}
if (x > nums.Length)
{
while (y <= nums1.Length)
{
nums2[z] = nums1[y];
z++;
y++;
}
if (y > nums1.Length)
{
while (x <= nums.Length)
{
nums2[z] = nums[x];
z++;
x++;
}
}
}
string merge = nums2[z].ToString();
textBox4.Text = merge;
}
}
First, an IndexOutOfRangeException
is not a compile error, it's a runtime error. 首先,
IndexOutOfRangeException
不是编译错误,而是运行时错误。
The indexes in an array are 0-based. 数组中的索引从0开始。 This means for example that an array of length 3 has indexes 0, 1 and 2, but index 3 doesn't exist and is out of range.
例如,这意味着长度为3的数组的索引为0、1和2,但索引3不存在且超出范围。 To fix your error change
<=
to <
on the following lines: 要解决您的错误,请在以下几行中将
<=
更改为<
:
while (x < nums.Length && y < nums1.Length)
while (y < nums1.Length)
while (x < nums.Length)
etc... 等等...
There may be other errors in your program too - this was just the first one I saw. 您的程序中可能还会存在其他错误-这只是我看到的第一个错误。
Arrays are zero-based in C# , meaning that the first item in the array is at index 0, not index 1. 数组在C#中从零开始 ,这意味着数组中的第一项位于索引0,而不是索引1。
However, the Length
property returns a one-based count of the number of objects in the array. 但是,
Length
属性返回数组中对象数的从一开始的计数。 So when you write x <= nums.Length
, you're actually trying to access an index that it outside of the bounds of the array. 因此,当您编写
x <= nums.Length
,您实际上是在尝试访问一个超出数组范围的索引。
Instead, you should rewrite that section of your code as: 相反,您应该将代码的该部分重写为:
while (x < nums.Length && y < nums1.Length)
{
if (nums[x] <= nums1[y])
{
nums2[z] = nums[x];
x++;
}
// etc.
索引从0
开始,因此您应该执行以下操作:
while (x < nums.Length && y < nums1.Length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.