0

I want to create a simple do-while statement that makes sure the user input is either Y or N and if not asks them to input again. If it is Y or N then the app continues. This is what I have so far but my application though it is just stuck in a loop asking the user input. New to C# -- thanks for any help.

    string answer = "";
    do
    {
        //Ask the user if they want to roll the dice
        Console.WriteLine("Would you like to roll the dice (y or n)?");
        //Get the user's response and validate that it is either 'y' or 'n'.
        answer = Console.ReadLine();
    } while (answer != "Y" || answer != "N");
1
  • So even if the user enters "n", the loop should continue asking if they want to roll the dice? That doesn't seem very intuitive. Commented Oct 24, 2013 at 1:53

4 Answers 4

2

Looks like a simple boolean logic error.

Your while statement should be: while (answer != "Y" && answer != "N");

Since you want to be sure that the answer is not yet Y and the answer is also not yet N. Loop while it is neither. Hope this helps!

Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it. At the moment if you enter a "Y" the condition answer != "N" will be true and if you enter a "N" the condition answer != "Y" will be true so you're stuck.
I thought that || was or and && was and? My logic was that it cannot be both Y and N so it was either or... I just tried && and it worked but I don't really understand why it worked.
Regardless thank you... I've spent longer than I'd like to admit trying to figure it out.
Boolean logic can be a real brain bender sometimes. Please accept answer if it works for you. Thanks!
1

Your logic is OR || instead of AND &&. It will always either not be Y or not be N because it cannot be BOTH at once. When it's N it isn't Y and the opposite is also true.

Use AND && instead.

Also, your comparison is case sensitive. Consider checking for upper and lower case.

Comments

1

2 things

  1. As all said replace || with &&
  2. Match uppercase of what user enter with your Y & N cause user can enter y. A Y and y, both are positive decisions of user.

answer.ToUpper() != "Y" && answer.ToUpper() != "N"

Comments

1

Change the || to an && and this should fix it for you.

Another way to look at it could be this:

The break conditions is whenever the answer is "Y" or the answer is "N".

You want the loop to continue whenever the break condition is not met so you can have

(answer == "Y" || answer == "N") and then not the result

while(!(answer == "Y" || answer == "N")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.