如何让控制台写几个随机字符串,例如
string Test1 = "Test Hello!";
string Test2 = "Test2 Hello hows your day!";
string Test3 = "How are you today sir?";
我如何制作一个随机输出这些字符串的程序?
答案 0 :(得分:1)
解决方案非常简单:
Random rnd = new Random();
//List of all your strings in which we will select a random index
List<string> sentences = new List<string>
{
"Test Hello!",
"Test2 Hello hows your day!",
"How are you today sir?"
};
//Write one of the sentences randomly thanks to [rnd.Next][1]
Console.WriteLine(sentences[rnd.Next(sentences.Count)]);
答案 1 :(得分:0)
这是一个解决方案,可以从列表中打印一个随机字符串x次:
var random = new Random();
var sentences = new List<string>
{
"Test Hello!",
"Test2 Hello hows your day!",
"How are you today sir?"
};
Console.Write("How many random sentences would you like to print?: ");
var count = 0;
// Convert user input into the integer count variable, and continually print an error message
// if the input is not an integer or if the integer is less than 0
while (!int.TryParse(Console.ReadLine(), out count) || count < 0)
{
Console.WriteLine("Please enter a positive integer: ");
}
// Print out a random sentence for x (count) amount of times.
while (count > 0)
{
// Will generate an index within the range of the list
var index = random.Next(0, sentences.Count() - 1);
Console.WriteLine(sentences[index]);
count--;
}
// Prevents the console from closing after the program is done executing.
Console.WriteLine("Press any key to exit the application...");
Console.ReadKey();
答案 2 :(得分:0)
或者,您可以
Random random = new Random();
string[] testcases = new[] {
"Test Hello!",
"Test2 Hello hows your day!",
"How are you today sir?"
};
Console.WriteLine(testcases[random.Next(0, testcases.Length)]);
Console.WriteLine(testcases[random.Next(0, testcases.Length)]);
Console.WriteLine(testcases[random.Next(0, testcases.Length)]);