gpt4 book ai didi

c# - 检查用户输入是否在我的数组中

转载 作者:行者123 更新时间:2023-11-30 13:44:58 25 4
gpt4 key购买 nike

我想检查用户输入是否在我的数组中。如果不是,则应写入“无效输入”。线阅读已经工作。我只想检查一下。但是就像我做的那样,它不起作用。听说要用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));

关于c# - 检查用户输入是否在我的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33414133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com