Выберите случайную строку из текстового документа
Я сделал программу, которая попросит пользователя ввести 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 ответ
Вы не заполняете свой classNames
массив, если файл уже существует. Поэтому ваш increaseChances
Метод не может выбрать имя из него.