Console.WriteLine('What is your name, traveler?');
string mainName = Console.ReadLine();
Console.WriteLine('So, your name is ' + mainName + ' ? y/n');
char ans = Console.ReadKey;
if (ans == y)
{
Console.WriteLine('Nice, let me introduce myself now.');
}
else if(ans == n)
{
}
else
{
Console.WriteLine('Please insert either y or n.');
}
在上面的代码中,如何使else if
语句返回第三行,而else
语句将返回代码的第一行并从此处继续运行?
答案 0 :(得分:1)
您可以尝试使用do....While(true)
循环
Console.WriteLine("What is your name, traveler?");
string mainName = Console.ReadLine();
Console.WriteLine("So, your name is " + mainName + " ? y/n");
do
{
var ans = Console.ReadKey(true).Key;
if (ans == ConsoleKey.Y)
{
Console.WriteLine("Nice, let me introduce myself now.");
break;
}
else if (ans == ConsoleKey.N)
{
break;
}
Console.WriteLine("Please insert either y or n.");
} while (true);
注意
我将使用Console.ReadKey(true).Key
来获取键盘输入值,因为它是枚举。