Only allowing yes or no as an answer

  • A+
Category:Languages

I am a complete newbie and i am stuck on a small problem

I want the user to only be able to have yes or no as an answer.

This is what I came up with

    static public bool askBool(string question)     {         try         {             Console.Write(question);              if (Console.ReadLine() == "y")             {                 return true;             }             else             {                 return false;             }         }         catch (Exception)         {              throw new FormatException("Only y or n Allowed");         } 

The problem is entering any other letter then 'y' will result in false, how can I best solve this ?

Thank you in advance.

 


Here the method will only return true or false if user has entered true or false.If user enters any word the loop will just continue to ask him for input until he enters y or n

you can give it a try by doing following changes

static public bool askBool(string question) {    bool boolToReturn = false;    Console.Write(question);    while (true)    {       string ans = Console.ReadLine();       if (ans != null && ans == "y")       {           boolToReturn = true;           break;       }       else if ( ans != null && ans == "n")       {           boolToReturn = false;           break;       }       else       {           Console.Write("Only y or n Allowed");       }    }    return boolToReturn; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: