gpt4 book ai didi

c# - 在循环中获取用户确认

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:53 24 4
gpt4 key购买 nike

在使用 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;
}
}

对于在循环体中间做出退出决定的情况,这是一种常见的解决方案。

关于c# - 在循环中获取用户确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com