標籤:style blog color for re c
using System;namespace ZhuaJiu { class ZhuaJiu { public static void Main() { string[] person; int personNum; initPerson(out person, out personNum); zhuajiu(person, personNum); Console.ReadKey(); } public static void initPerson(out string[] person, out int personNum) { bool flag = true; personNum = 0; //檢測人數為數字 while (flag) { try { Console.Write("請輸入要抓鬮的人數:"); personNum = int.Parse(Console.ReadLine()); flag = false; } catch { Console.WriteLine("輸入的非數字,請重新輸入"); } } person = new string[personNum]; //檢測姓名非空 for (int i = 0; i < personNum; i++) { Console.Write("請輸入第{0}個人的姓名:", i + 1); flag = true; while (flag) { person[i] = Console.ReadLine(); if (person[i] == "" || person[i] == null) Console.Write("未輸入姓名,請重新輸入第{0}個人的姓名:", i + 1); else flag = false; } } } public static void zhuajiu(string[] person, int personNum) { Console.WriteLine("現在開始抓鬮..."); System.Random ran = new Random(); for (int i = 0; i < personNum; i++) { //每次產生最大不超過當前數組長度的隨機數,數組長度每次減1; int ranNow = ran.Next(personNum - i); Console.WriteLine("第{0}次的抓鬮結果是:{1}", i + 1, person[ranNow]); //每次把數組長度減1; delPerson(ref person, ranNow); } } public static void delPerson(ref string[] person, int ranNow) { string[] tempPerson = new string[person.Length - 1]; //在獲得的隨機數之後,均往前挪一位; for (int i = ranNow; i < (person.Length - 1); i++) { person[i] = person[i + 1]; } //每次把數組長度減1; for (int j = 0; j < person.Length - 1; j++) { tempPerson[j] = person[j]; } person = tempPerson; } }}