在循环中获取用户确认

get user confirmation inside a loop

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

您应该更改循环的终止条件
应该是 while(!confirmChoice);
并且您应该将 break; 行更改为 continue;

你的条件有误,应该是while(confirmChoice==false),不要使用break;

 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();
        }
        else
        {
            confirmChoice = true;
        }
        }while(confirmChoice==false);
    }

您的代码几乎是正确的 - 您需要做的就是将 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;
    }
}

这是在循环体中间做出退出决定的情况下的常见解决方案。