-2
我正在編寫一個代碼,要求用戶輸入他的名字,以及他是否想讀一個笑話。答案應限於y或n。任何其他角色都應被視爲無效,並應循環回問題。這是我迄今爲止所做的。限制用戶輸入y或n並相應地在C#中顯示結果
static void Main(string[] args)
{
string name="";
string KeyChar;
Console.WriteLine("Hello, what is your name?");
name=Console.ReadLine();
Console.WriteLine("Greetings, " + name + ". Would you like to read a joke? (y/n)");
ConsoleKeyInfo result = Console.ReadKey();
Console.WriteLine("\n");
while (true)
{
while ((result.KeyChar != 'Y') || (result.KeyChar != 'y') || (result.KeyChar != 'N') || (result.KeyChar != 'n'))
{
Console.WriteLine("Invalid key. Limit your answer to y or n");
break;
}
while ((result.KeyChar == 'Y') || (result.KeyChar == 'y') || (result.KeyChar == 'N') || (result.KeyChar == 'n'))
{
if ((result.KeyChar == 'Y') || (result.KeyChar == 'y'))
{
Console.WriteLine("Joke question?");
Console.ReadLine();
Console.WriteLine("Joke answer.");
break;
}
else if ((result.KeyChar == 'N') || (result.KeyChar == 'n'))
{
Console.WriteLine("You're missing on all the fun! Suit yourself. Goodbye!");
break;
}
}
}
}
result = Console.ReadKey();在while(true)的最後,用ifs替換你的兩個內在的whiles。 – Master117