在使用 do-while 循环搜索解决方案后,我现在卡在了这一点上,无法弄清楚我做错了什么。
static void StartUp()
{
bool confirmChoice = false;
Console.WriteLine("Hey, Enter your Character Name!");
string name = Console.ReadLine();
do
{
Console.WriteLine("Is " + name + " correct? (y) or would you like to change it (n)?");
string input = Console.ReadLine();
if (input == "n")
{
Console.WriteLine("Allright, enter your new Name then!");
name = Console.ReadLine();
break;
}
else
{
confirmChoice = true;
}
}while(confirmChoice);
}
请您参考如下方法:
您的代码几乎是正确的 - 您需要做的就是将 do/while 循环的条件反转为 while (!confirmChoice)
但是,您可以做得更好:制作一个永远的循环,然后使用 break 退出它:
while (true) {
Console.WriteLine("Please, Enter your Character Name!");
string name = Console.ReadLine();
Console.WriteLine("Is " + name + " correct? (y) or would you like to change it (n)?");
string input = Console.ReadLine();
if (input == "y") {
break;
}
}
对于在循环体中间做出退出决定的情况,这是一种常见的解决方案。
