2010-12-18 159 views
1

我想編寫合併排序算法,當我調試程序並給它的數字,它goves索引超出範圍錯誤,我的代碼是什麼問題?提前感謝。編譯錯誤:索引超出範圍

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; 

    } 
} 

回答

4

首先,IndexOutOfRangeException不是編譯錯誤,這是一個運行錯誤。

數組中的索引是從0開始的。這意味着例如長度爲3的數組具有索引0,1和2,但是索引3不存在並且超出範圍。要改正錯誤變化對以下行<=<

while (x < nums.Length && y < nums1.Length) 

while (y < nums1.Length) 

while (x < nums.Length) 

等等

有可能是你的程序中其他錯誤太多 - 這只是我第一個看到的。

+0

解決了,謝謝你,但你說有其他的問題,也因爲它給出了輸出0 – Arash 2010-12-18 08:00:25

1

數組從零開始在C#,意味着陣列中的第一項是在索引0,而不是索引1

然而,Length屬性返回的數目的一個基於一個計數數組中的對象。所以當你寫x <= nums.Length時,你實際上試圖訪問一個超出數組邊界的索引。

相反,你應該重寫爲你的代碼的那一段:

while (x < nums.Length && y < nums1.Length) 
    { 
     if (nums[x] <= nums1[y]) 
     { 
      nums2[z] = nums[x]; 
      x++; 

     } 

    // etc. 
+0

的問題解決,謝謝 – Arash 2010-12-18 07:59:22

0

指數從0開始,所以你應該做的:

while (x < nums.Length && y < nums1.Length)