Joshua
Joshua

Reputation: 41

Ignore input until valid response?

Sorry if this is similar to an existing question - I did try looking!

Anyhow, I've got a program going as follows:

    static void Main(string[] args)
    {
        string temp;

        Console.WriteLine("question");
        temp = Console.ReadLine();

        if (temp == "a")
        {
            Console.WriteLine("Incorrect");
        }
        if (temp == "b")
        {
            Console.WriteLine("Incorrect");
        }
        if (temp == "c")
        {
            Console.WriteLine("Correct");
        }
        else
        {
            Console.WriteLine("Not a valid response");
        }

    }

And I'm trying to get it to ignore invalid responses until I give a valid response. If for example, I needed to press the key a, or b, or c but I pressed d, it would just tell me my answer isn't a valid option and wait until I gave a valid response.

Upvotes: 0

Views: 538

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You can implement (extract) a method:

 private static char AnswerTheQuestion(string question, int answers) {
   Console.WriteLine(question);

   // Loop until...
   while (true) {
     // Let's be nice and tolerate leading / trailing spaces
     string answer = Console.ReadLine().Trim();

     if (answer.Length == 1) {
       char result = char.ToLower(answer[0]); // let's ignore case ('A' == 'a' etc.)

       if (result >= 'a' && result <= 'a' + answers)
         return result; // ...user provide an answer in expected format
     }

     // Comment it out if you want just to ignore invalid input 
     Console.WriteLine($"Sorry, provide an answer in [a..{(char)('a' + answers)}] range");
   }
 }

Then you can use it:

   static void Main(string[] args) { 
     char result = AnswerTheQuestion(string.Join(Environment.NewLine,
           "What is the capital of Russia?",
           "  a. Saint-Petersburg",
           "  b. Moscow",
           "  c. Novgorod"),
       3);

     Console.WriteLine($"{(result == 'b' ? "correct" : "incorrect")}");

     Console.ReadKey(); 
   }

Upvotes: 1

AliReza Sabouri
AliReza Sabouri

Reputation: 5255

void Main()
{
    string temp;

    Console.WriteLine("question");
    while (true)
    {
        temp = Console.ReadLine();

        if (temp == "a")
            Console.WriteLine("Incorrect"); 
        else if (temp == "b")
            Console.WriteLine("Incorrect");
        else if (temp == "c")
            Console.WriteLine("Correct");
        else if (temp == "exit") // providing a way to exit the loop
            break;
        else { } // ignore input            
    }
}

Upvotes: 0

Stefano Balzarotti
Stefano Balzarotti

Reputation: 1904

Not sure if this is what you intend:

public static void Main()
        {
            Console.WriteLine("question");
            bool tryAgain;
            do
            {
                tryAgain = true;
                var key = Console.ReadKey();
                switch (key.KeyChar)
                {
                    case 'a':
                    case 'b':
                        Console.WriteLine();
                        Console.WriteLine("Incorrect");
                        tryAgain = false;
                        break;
                    case 'c':
                        Console.WriteLine();
                        Console.WriteLine("Correct");
                        tryAgain = false;
                        break;
                    default:
                        Console.Write("\b \b");
                        break;
                }
            } while (tryAgain);
        }

All inputs are ignored except valid inputs ('a', 'b', 'c') if you type 'd' inputs is ignored.

UPDATE this version works with Enter to confirm input:

public static void Main()
        {
            Console.WriteLine("question");
            bool tryAgain;
            bool enterPressed;
            char input = ' ';
            do
            {
                enterPressed = false;
                do
                {
                    tryAgain = true;
                    var key = Console.ReadKey();
                    switch (key.KeyChar)
                    {
                        case 'a':
                        case 'b':
                        case 'c':
                            input = key.KeyChar;
                            tryAgain = false;
                            break;
                        default:
                            Console.Write("\b \b");//Delete last char
                            break;
                    }
                } while (tryAgain);
                var confirmkey = Console.ReadKey();
                if (confirmkey.Key == ConsoleKey.Enter)
                {
                    enterPressed = true;
                    Console.WriteLine();
                }
                else
                {
                    Console.Write("\b \b"); //Delete last char
                }
            } while (!enterPressed);
            switch (input)
            {
                case 'a':
                case 'b':
                    Console.WriteLine("incorrect");
                    break;
                case 'c':
                    Console.WriteLine("correct");
                    break;
            }
        }

Upvotes: 1

Christopher
Christopher

Reputation: 9824

This is the textbook case for both do...while loops and switch/case statements. Asuming "a" is still a valid input:

bool validInput = false;

do{
  Console.WriteLine("question");
  string input = Console.ReadLine();

  switch(input){
    case "a":
      Console.WriteLine("Incorrect");
      validInput = true;
      break;
    //other cases and default omitted
  }

}while(!validInput);

Upvotes: 0

Related Questions