简体   繁体   中英

C# Do-While statement to validate user input

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");

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!

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.

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")

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM