检查用户输入是否在我的数组中
本文关键字:我的 数组 是否 用户 输入 检查 | 更新日期: 2023-09-27 18:19:42
我想检查用户输入是否在我的数组中。如果不是,则应写入"无效输入"。行读取已经起作用。我只是想看看这个。但就像我做的那样,它不起作用。我听说我要用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()
[...]
我宁愿将集合类型从数组更改为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));
尝试:
using System.Linq;
...
if (!menuChars.Contains(userKeyPress))
...
您可以尝试lik 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");
}