简体   繁体   中英

Index was outside the bounds of the array - integers

I have just run across a problem which is common but I'm not sure why it's happening in this instance.

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;    
}

It will accept the number in the first TextBox (es) fine. As soon as it moves onto the catch section it will pop up with an error Index was outside the bounds of the array Is there something obvious I'm missing? or is this quite unique to my program?

我以为您认为您的数组从1到6。从0到5。

You should ensure that your TextBox contains at least 6 characters else it gives an exception:

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

And then remember that the index of the array starts from 0 not 1 .

How many chars are in the input string s = textBox1.Text; ? You don't perform any check on the user input.

For example

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

then, when you try to use index 4/5/6 you get the error.
Of course, you should also consider that arrays indexes start at zero not at one.
In my input above, you will have only index from 0 to 3.

A simple check should be (Assuming you've already ruled out non-numeric data by other means)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM