get user confirmation inside a loop

185 views Asked by At

After searching for a Solution with a do-while Loop, I'm now stuck and this point, and just cant figure out what I am doing wrong.

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

There are 3 answers

1
Sergey Kalinichenko On BEST ANSWER

Your code is almost right - all you need to do is inverting the condition of your do/while loop to while (!confirmChoice)

However, you could do better than that: make a forever loop, and use break to exit it:

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;
    }
}

This is a common solution for situations when the decision to exit is made in the middle of the loop body.

0
Hamid Pourjam On

you should change the termination condition for your loop
it should be while(!confirmChoice);
and you should change the break; line to continue;

0
TeamKhurram On

Your Condition is wrong it should be while(confirmChoice==false) and don't use 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);
    }