Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 索引超出了数组整数的界限_C#_Arrays_Winforms_Indexing - Fatal编程技术网

C# 索引超出了数组整数的界限

C# 索引超出了数组整数的界限,c#,arrays,winforms,indexing,C#,Arrays,Winforms,Indexing,我刚刚遇到了一个常见的问题,但我不确定为什么会发生在这种情况下 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 {

我刚刚遇到了一个常见的问题,但我不确定为什么会发生在这种情况下

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

它将接受第一个文本框中的数字。当它移动到catch部分时,它会弹出一个错误索引,该索引超出了数组的边界,是否有明显的遗漏?或者这对我的程序来说是非常独特的吗?

我想你认为你的数组是从1到6的。
它是从0到5。

我想你认为你的数组是从1到6的。
从0到5。

您应该确保文本框至少包含6个字符,否则会出现异常:

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

然后记住数组的索引从0开始,而不是从1开始。

您应该确保文本框至少包含6个字符,否则会出现异常:

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

然后记住数组的索引从0开始,而不是从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
    .......

输入字符串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
    .......

数组索引从0开始,您从1开始。这可能是原因吗?数组索引从0开始,而从1开始。这可能是原因吗?