向數組中添加一個元素


實現效果:

  

知識運用:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM