首页 > 代码库 > C# 抓阄 练习,再不济好歹是自已写的,多练练吧,待改进

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