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

本文关键字:随机 字符串 选择 文本 文档 | 更新日期: 2023-09-27 18:21:57

我制作了一个程序,要求用户在文本文档中输入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);
        }
    }
}

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

如果文件已经存在,则不会填充classNames数组。因此,您的increaseChances方法无法从中选择名称。