向数组中添加一个元素

Posted on 2018-12-03 02:32  努力成长静待花开  阅读(2361)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  Array对象的Length属性 int类的tryParse()方法

实现代码:

        int[] int_arr;
        //"随机数组"按钮事件
        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();                   //清掉多余内容
            int_arr = new int[10];
            label1.Text = "";
            for (int i = 0; i < 10;i++ ){
                int_arr[i]=(new Random()).Next(0,9);
                System.Threading.Thread.Sleep(30);  //添加休眠 避免数字相同
                label1.Text += int_arr[i] + "  ";
            } 
        }
        //"添加"按钮事件
        private void button2_Click(object sender, EventArgs e)
        {   int site,value;
        if ((label1.Text != string.Empty) && (int.TryParse(textBox1.Text, out site)) &&
            (int.TryParse(textBox2.Text, out value)))   //进行了安全设置
        {
                foreach(int i in AddArray(int_arr,int.Parse(textBox1.Text),int.Parse(textBox2.Text))){
                    richTextBox1.Text += i + " ";
                }
        }
        else { MessageBox.Show("请填写完整"); }
        }
        //定义插入的方法
        public int[] AddArray(int[] ArrayBorn,int Index,int Value) {
            if (Index >= ArrayBorn.Length)      //判断索引大于等于数组长度
                Index = ArrayBorn.Length;   //设置索引长度为数组长度
            int[] temArray=new int[ArrayBorn.Length+1]; //创建插入后的新数组
            for (int i = 0; i < temArray.Length;i++ )   //遍历新数组
            {
                if (Index >= 0)                       //索引大于等于零
                {
                    if (i < Index )
                        temArray[i] = ArrayBorn[i];
                    else if (i == Index)
                        temArray[i] = Value;
                    else
                        temArray[i] = ArrayBorn[i - 1];
                }
                else {                              //索引小于零
                    if (i == 0)
                        temArray[i] = Value;    //添加值在首位
                    else
                        temArray[i] = ArrayBorn[i - 1];
                }
            } 
                return temArray;
        }