1

我有这个错误:索引超出范围。必须是非负数且小于集合的大小。

我花了很长时间试图解决它,但我无法解决。请我需要帮助

public partial class Form1 : Form
    {
        string[] generate = new string[] {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Name14","Name15","Name16","Name17","Name18","Name19","Name20" };
        string[] n = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15", "Name16", "Name17", "Name18", "Name19", "Name20" };
        String[] a = new String[20];
        string name;
        int Num;

        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e) // START btn
        {
            Num = int.Parse(textBox1.Text);
            if (Num < 20)
            {
                if (generate.Length >= Num)
                {
                    for (int i = Num; i > 0; i--)
                    {

                        name = generate.ElementAt(i);
                        listBox1.Items.Add(name); // Print it to list1 
                        generate = generate.Where(s => s != name).ToArray(); // Delete name after using
                    }
                }
                else MessageBox.Show("Sorry, remaining names =" + generate.Length);
                listBox2.Items.Clear();
                listBox2.Items.AddRange(generate);

            }
            else MessageBox.Show("Max name is 20!");

        }
4

3 回答 3

0

问题是 20 个元素数组中的索引从 0 到 19。在您的代码中,您允许 20,这会出错

if (generate.Length >= Num)

你应该删除=标志。此外,您应该=在 for 循环中添加符号

for (int i = Num; i > 0; i--)

因此您可以包含数组的第一个元素(索引为 0 的元素)。

基本上,如果条件应如下所示:

if (generate.Length > Num)

和这样的循环:

for (int i = Num; i >= 0; i--)
于 2013-06-15T22:58:21.800 回答
0

尝试 19 而不是 20,因为当您计算数组中的元素时,您从零开始。

于 2013-06-15T22:59:15.637 回答
0

这将让您在文本框中放置 20

            Num = int.Parse(textBox1.Text);
            if (Num <= 20)
            {
                if (generate.Length >= Num)
                {
                    for (int i = Num - 1; i >= 0; i--)
                    {

                        name = generate.ElementAt(i);
                        listBox1.Items.Add(name); // Print it to list1 
                        generate = generate.Where(s => s != name).ToArray(); // Delete name after using
                    }
                }
                else MessageBox.Show("Sorry, remaining names =" + generate.Length);
                listBox2.Items.Clear();
                listBox2.Items.AddRange(generate);

            }
            else MessageBox.Show("Max name is 20!");
于 2013-06-16T00:05:33.547 回答