从文本文档中选择随机字符串

时间:2014-09-16 07:42:21

标签: c# text console document

我制作了一个程序,要求用户在文本文档中输入20个名字。如果该文件不存在,则创建一个新文件,如果存在,则显示内容。

我要做的是使用随机数随机选择一个名字,我已经在这里完成了但是我无法让它工作。我希望它读取文本文件并从中随机选择一个名称。 我没有错误,也不确定我做错了什么。

注意:我所做的是输入的第一个名字(数组中的classNames [0]),以增加被选中的机会。

static void increaseChances()
{
    int rand = r.Next(3); //0 = 100%, 1 = 50%, 2 = 33.33% chance, 3 = 25% chance, This number determines the percentage of the first name entered to be picked

    if (rand == 0)
    {
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", classNames[0]);
    }
    else
    {
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", classNames[r.Next(classNames.Length)]);
        Console.ForegroundColor = ConsoleColor.White;
    }
}

这就是我所拥有的:

class Program
{
    static Random r = new Random();
    static string[] classNames = new string[20];

    static void increaseChances()
    {
        int rand = r.Next(3); //0 = 100%, 1 = 50%, 2 = 33.33% chance, 3 = 25% chance, This number determines the percentage of the first name entered to be picked

        if (rand == 0)
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", classNames[0]);
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", classNames[r.Next(classNames.Length)]);
            Console.ForegroundColor = ConsoleColor.White;
        }
    }

    static void Main(string[] args)
    {
        Random RandString = new Random();

        string file = @"C:\names.txt";
        Console.ForegroundColor = ConsoleColor.White;

        if (File.Exists(file))
        {
            Console.WriteLine("Names in the text document are: \n");
            foreach (string displayFile in File.ReadAllLines(file))
            Console.WriteLine(displayFile);
            increaseChances();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("\nPress any key to close... ");
            Console.ReadKey();
        }
        else
        {
            for (int i = 0; i < 20; i++) 
            {
                Console.Write("Enter name number {0}: ", i + 1);
                classNames[i] = Console.ReadLine();
                File.Create(file).Close();
                File.WriteAllLines(file, classNames);
            }

                Console.WriteLine("Writing names to file...");
                increaseChances();
                Thread.Sleep(3000);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Completed! Exiting...");
                Thread.Sleep(1500);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果文件已存在,则表示您未填写classNames数组。因此,increaseChances方法无法从中选择名称。