C#程序設計(十三)----獲取題庫中的試題號

* 程序的版權和版本聲明部分
* Copyright (c) 2012, 煙臺大學計算機學院學生
* All rights reserved.

* 作 者: 劉鎮
* 完成日期: 2012 年 10 月 27 日
* 版 本 號: 3.013

* 對任務及求解方法的描述部分

* 問題描述:假定已經獲取題庫中的試題號,並存放在數組arrayKT中,方法實現從上述數組中隨機抽出給定數量(n,1<=n<=arrayKT.Length)的考題,並組成一個考題字符串。

*代碼部分:

 

TestString.cs:

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyTestString
{
    class TestString
    {
        public static string getKTH(int n, int[] arrayKT)
        {
            Random random = new Random();
            int num = 0;
            string resultStr = "";
            if(n > arrayKT.Length)
            {
                Console.WriteLine("超出題庫的總題目數目!");
                return "";
            }

            for (int i = 0; i < n; i++)
            {
                while(true)
                {
                    num = random.Next(arrayKT.Length);
                    if (arrayKT[num] != 0)
                    {
                        break;
                    }
                }

                resultStr = resultStr.Insert(resultStr.Length, arrayKT[num].ToString());

                if (i != n - 1)
                {
                    resultStr = resultStr.Insert(resultStr.Length, ",");
                }

                arrayKT[num] = 0;
            }

            return resultStr;
        }
    }
}


 

 

 

 

測試類(Program.cs):

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyTestString
{
    class Program
    {
        static void Main(string[] args)
        {
            int [] arrayKT = {10, 13, 18, 19, 20, 22, 30, 31, 39, 40, 44, 45, 41, 50};
            string result = TestString.getKTH(14, arrayKT);
            Console.WriteLine("題庫中的試題號: " + result);
            Console.ReadKey();
        }
    }
}


 

 

 

測試結果:

 

 

 

 

 

 

 

 

心得經驗:

 

這個問題有幾個主要點:1、超出總題目數的情況;2、隨機數類:最大數的限制是傳入的數組的長度;3、組成考題字符串中考題不重複:通過將已經取出的隨機數的數組賦值爲0;從而實現字符串不重複。4、在字符串中添加新字符串,用到了Insert(),但是一定要記住字符串的Insert()是生成新字符串而不是在就字符串上處理。

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章