3

I want to check if the user input is in my array. If it's not it shall write "Invalid input". The line reading already works. I just want to check this. But like I did it, it doesn't work. I heard that I shall use a for loop. But how?

[...]
char[] menuChars = { 'e', 'E', 'l', 'L', 'k', 'K', 't', 'T', 's', 'S', 'b', 'B' };

if (userKeyPress == !menuChars)
        {
          Console.WriteLine("Please insert a valid char: ");
        }
Console.ReadLine()
[...]
3
  • if(!menuChars.Contains(userKeyPress))? Commented Oct 29, 2015 at 12:24
  • @SonerGönül Yes. If, for some reason, you do not want to use Linq, given that the menuChars is a one-dimensional zero-indexed array, you will have to do either if (Array.IndexOf(menuChars, userKeyPress) == -1) or if (!((ICollection<char>)menuChars).Contains(userKeyPress)). Those are the .NET 2.0 ways. Commented Oct 29, 2015 at 13:35
  • @JeppeStigNielsen Hmm, I see.. Commented Oct 29, 2015 at 13:38

3 Answers 3

6

I'd rather change the collection type from array to HashSet<Char>:

  HashSet<Char> menuChars = new HashSet<Char>() {
    'e', 'E', 'l', 'L', 'k', 'K', 't', 'T', 's', 'S', 'b', 'B'
  };

  ...

  Char userKeyPress;

  // and condition check from "if" to "do..while" 
  // in order to repeat asking user until valid character has been provided
  do {
    Console.WriteLine("Please insert a valid char: ");
    // Or this:
    // userKeyPress = Console.Read();
    userKeyPress = Console.ReadKey().KeyChar;
  }
  while (!menuChars.Contains(userKeyPress));
Sign up to request clarification or add additional context in comments.

2 Comments

When I paste this in my code "Console.ReadLine()" is red underlined and it doesn't work. What part of code can I send you to help you understanding my code?
@user5462581: depending on what do you mean by "insert a valid char" it could be either Console.Read(); or Console.ReadKey().KeyChar;; I'm sorry for typo.
2

Try:

using System.Linq;
...
if (!menuChars.Contains(userKeyPress))
...

2 Comments

That worked. Thanks. And how can I repeat the line "Input valid char" until the user typed a valid one?
Glad to hear. I believe Dmitry Bychenko's answer show how to repeat the check.
1

You can try lik ethis:

if(menuChars.Contains(userKeyPress))
{
     Console.WriteLine("Found");
}
else
{
   Console.WriteLine("Not Found");
}

or like this:

if(Array.IndexOf(menuChars, userKeyPress) > -1)
{
   Console.WriteLine("Found");
}
else
{
   Console.WriteLine("Not Found");
}

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.