我想检查用户输入是否在我的数组中。如果不是,则应写入"无效输入"。线读已经有效。我只想检查一下。但就像我做的那样,它不起作用。我听说我将使用for循环。但是如何?
[...]
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()
[...]
答案 0 :(得分:6)
我宁愿将集合类型从数组更改为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));
答案 1 :(得分:2)
尝试:
menu.setMainPage(...)
答案 2 :(得分:1)
你可以试试ethis:
if(menuChars.Contains(userKeyPress))
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not Found");
}
或者像这样:
if(Array.IndexOf(menuChars, userKeyPress) > -1)
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not Found");
}