在循环中获取用户确认

时间:2015-06-14 17:41:14

标签: c# .net do-while

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您的情况有误,应该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);
    }