1. 程式人生 > >向陣列中新增一個元素

向陣列中新增一個元素

實現效果:

  

知識運用:

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