I'm trying to make a program that prints number in a loop, but when "X" is pressed the program should stop (in theory).
It isn't working until a button is pressed. When i hold any button it gets in a loop but the loop should start with the beggining.
Code:
static void Main(string[] args)
{
Random rnd = new Random();
string[] k = { "1", "2", "3", "4", "5", "6" };
while (true)
{
Console.WriteLine(k[rnd.Next(1, 6)]);
if (Console.ReadKey(true).Key == ConsoleKey.X)
{
break;
}
}
Console.ReadKey();
}
Only read a key when there is one pressed:
//if (Console.ReadKey(true).Key == ConsoleKey.X)
if (Console.KeyAvailable && ReadKey(true).Key == ConsoleKey.X)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.