RobertNewToJava
RobertNewToJava

Reputation: 61

Only allowing yes or no as an answer

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);
        return Console.ReadLine() == "y";
    }
    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.

EDIT (from comment question)

try
{
    Console.Write(question);
    return int.Parse(Console.ReadLine());
}
catch (Exception)
{
    throw new FormatException("Please Enter a Number");
}

Upvotes: 4

Views: 5834

Answers (6)

NexX
NexX

Reputation: 323

Here another idea:

public static bool ReadUserYesOrNo()
{
    bool userSaysYes = true;
    Console.Write("Y\b");

    bool done = false;
    while (!done)
    {
        ConsoleKeyInfo keyPressed = Console.ReadKey(true); // intercept: true so no characters are printed
        switch (keyPressed.Key) {
            case ConsoleKey.Y:
                Console.Write("Y\b"); // print Y then move cursor back
                userSaysYes = true;
                break;
            case ConsoleKey.N:
                Console.Write("N\b"); // print N then move cursor
                userSaysYes = false;
                break;
            case ConsoleKey.Enter:
                done = true;
                Console.WriteLine();
                break;
        }
    }
    return userSaysYes;
}

This will print the default value Y to the console. By pressing Y or N the user can toggle between the two values. The character in the console output will be overwritten. Pressing 'enter' selects the choice and the method returns the result.

Upvotes: 0

Fabjan
Fabjan

Reputation: 13676

A bit more simplified version of Dmitry's answer with switch (what I normally do for this kind of scenarios):

static public bool askBool(string question)
{  
    while(true)
    {
        Console.Clear();
        Console.Write(question);
        var input = Console.ReadLine().Trim().ToLowerInvariant();
        switch (input)
        {
            case "y":
            case "yes": return true;

            case "n":
            case "no": return false;
        }
    }
}

Also I'd consider changing .ReadLine() to .ReadKey() because what we really need here is just 'y' or 'n'... One key is enough.

We use Exceptions mostly for scenarios when unexpected value will lead to some error. We don't throw an exception when we expect user to enter rubbish values and handle them.

Upvotes: 3

Lucifer
Lucifer

Reputation: 1594

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

Answer to second question:-

`

    public static int askInt(string question)
        {
           Int intToReturn = false;
           Console.Write(question);
           while (true)
           {
              string ans = Console.ReadLine();
              if (int.TryParse(and,out intToreturn))
                  break;
              else
                  Console.Write("Only number Allowed");
           }
           return intToReturn;
        }`

Upvotes: 3

Carra
Carra

Reputation: 17964

You want to throw the exception, not catch it. Example:

static public bool askBool(string question)
{
    Console.Write(question);
    var input = Console.ReadLine();
    if (input == "y")
    {
        return true;
    }
    else if(input == "n")
    {
        return false;
    }
    else//It's not y or n: throw the exception.
    {
        throw new FormatException("Only y or n Allowed");
    }
}

Of course, you must then capture the 'FormatException' where you call this method.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I doubt if you want an exception to be thrown - there's nothing exceptional if the user puts OK instead of yes; I suggest to keep asking until "yes" or "no" are read:

   public static AskBool(string question) {
     while (true) {
       // If we have a question to ask (the question is not empty one)...
       if (!string.IsNotNullOrWhiteSpace(question)) 
         Console.WriteLine(question); // ... ask it

       // Trim: let be nice and trim out leading and trailing white spaces
       string input = Console.ReadLine().Trim();

       // Let's be nice and accept "yes", "YES", "Y" etc.
       if (string.Equals(input, "y", StringComparison.OrdinalIgnoreCase) || 
           string.Equals(input, "yes", StringComparison.OrdinalIgnoreCase))
         return true;
       else if (string.Equals(input, "n", StringComparison.OrdinalIgnoreCase) || 
                string.Equals(input, "no", StringComparison.OrdinalIgnoreCase))
         return false;

       // In case of wrong user input, let's give a hint to the user
       Console.WriteLine("Please, answer yes or no (y/n)");
     } 
   } 

Upvotes: 4

Robert Chan
Robert Chan

Reputation: 142

Something like this?

if (Console.ReadLine() == "y")
            {
                return true;
            }
            else if (Console.ReadLine() == "n")
            {
                return false;
            }
            else {
              throw new Exception("only y and n allowed...");
            }

Upvotes: 0

Related Questions