2012-11-04 15 views
1

我剛剛遇到了一個常見的問題,但我不確定爲什麼在這種情況下發生了這個問題。索引超出了數組的範圍 - 整數

string s; 
int c1, c2, c3, c4;  

private void button2_Click(object sender, EventArgs e) 
{ 
    String number; 
    s = textBox1.Text; 
    int[] d = s.Select(c => (int)c - (int)'0').ToArray(); 

    try 
    { 
     c1 = (4 * d[1] + 10 * d[2] + 9 * d[3] + 2 * d[4] + d[5] + 7 * d[6]) % 11; 
     c2 = (7 * d[1] + 8 * d[2] + 7 * d[3] + d[4] + 9 * d[5] + 6 * d[6]) % 11; 
     c3 = (9 * d[1] + d[2] + 7 * d[3] + 8 * d[4] + 7 * d[5] + 7 * d[6]) % 11; 
     c4 = (d[1] + 2 * d[2] + 9 * d[3] + 10 * d[4] + 4 * d[5] + d[6]) % 11; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 

    number = d[1]+d[2]+d[3]+d[4]+d[5]+d[6]+c1+c2+c3+c4.ToString(); 
    textBox2.Text = number;  
} 

它會接受第一個TextBox罰款的號碼。只要它移動到捕捉部分,它會彈出一個錯誤Index was outside the bounds of the array有什麼明顯的我失蹤了嗎?或者這對我的程序來說很獨特?

+0

數組索引從0開始,你從1開始。這可能是原因嗎? –

回答

5

我bellieve,你認爲你的陣列去從1到6 它從0到5

1

你應該確保你TextBox包含至少6個字符否則它給出了一個例外:

if(textBox1.Text.Length >= 6) 
{ 
    //your code here 
} 
else 
    MessageBox.Show("You must insert at least 6 characters"); 

然後請記住,陣列的索引從0開始,而不是從1開始

1

輸入字符串中有多少個字符s = textBox1.Text;? 您不對用戶輸入執行任何檢查。

例如

textBox1.Text = "1234"; // only 4 digits 

那麼,當您嘗試使用索引4/5/6你的錯誤。
當然,你也應該考慮數組索引從零開始不是一個。
在我上面的投入,你會從0只指數3

一個簡單的檢查應(假設你已經排除了通過其他方式非數字數據)

s = textBox1.Text; 
if(s.Length != 6) 
    MessageBox.Show("6 digits required!"); 
else 
    .......