我怎么会让一个控制台写一些随机字符串,例如打印随机设置的字符串?
string Test1 = "Test Hello!";
string Test2 = "Test2 Hello hows your day!";
string Test3 = "How are you today sir?";
我怎么会让一个程序,随机输出那些字符串?
我怎么会让一个控制台写一些随机字符串,例如打印随机设置的字符串?
string Test1 = "Test Hello!";
string Test2 = "Test2 Hello hows your day!";
string Test3 = "How are you today sir?";
我怎么会让一个程序,随机输出那些字符串?
该解决方案是很容易的:
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)]);
当然,这取决于OP想要如何随机:-) – pm100
这里,将打印从时间列表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();
或者,你可以做
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)]);
显然你需要将这些数据放在某个地方,否则你必须在数组中对它们进行硬编码。 [和获得随机数](https://www.dotnetperls.com/random) –