我正在努力制作侮辱计划。我想使用数组来存储从a
到z
的整个字母表。我使用了if statement
所以当用户按下字母a
时会发生一些事情。并且,如果他按下任何东西而不是一封信,那么就会发生其他事我现在被困住了。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type any bastard letter!!!");
ConsoleKeyInfo keyInfo = Console.ReadKey();
char[] array1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
if (keyInfo.KeyChar == 'a')
{
SpeechSynthesizer synth = new SpeechSynthesizer();
Console.WriteLine("You have typed a letter");
synth.Speak("You have typed a letter");
}
else
{
SpeechSynthesizer synth = new SpeechSynthesizer();
Console.WriteLine(" ");
Console.WriteLine("did you type {0}", keyInfo.KeyChar.ToString());
synth.Speak("You have typed a bastard number you infentile pillock");
}
}
}
我假设当你说“使数组工作”时,你的意思是“我想测试开头输入的字母是否在数组中”。
char[] array1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
if (array1.Contains(keyInfo.KeyChar))
{
// user typed a letter
}
else
{
// user typed not a letter
}
我试图向您展示如何检查C#中是否存在某个数组。但是因为你的目标是检查角色是否是一个字母,所以甚至更好:Char.IsAlpha()
(documentation here)(以及IsDigit()
(documentation)。
在这种情况下,您根本不需要初始数组:
if (Char.IsAlpha(keyInfo.KeyChar))
{
// character is a letter (will work for both lowercase or uppercase)
}
else if (Char.IsDigit(keyInfo.KeyChar))
{
// character is a digit
}
else
{
// char is neither a digit or a letter
}
并且,最后另一种不涉及数组的方式,并且严格等同于您的初始方法(感谢评论中的@JeppeStigNielsen):
if (keyInfo.KeyChar >= 'a' && keyInfo.KeyChar <= 'z')
{
// character is a lowercase letter from English-alphabet
}
else if (keyInfo.KeyChar >= '0' && keyInfo.KeyChar <= '9')
{
// character is a digit
}
else
{
// char is neither a digit or a letter
}
这是因为char实际上是相应字符的代码编号,而字母(或数字)的代码是连续值。 see here for the list of Unicode codes
没有迭代,只需使用以下表达式:
if (array1.Contains(keyInfo.KeyChar)) // a letter has been typed...
{
// ...
}
else
{
// ...
}
您需要遍历数组并检查是否有任何符合用户输入的字符,但一个简单的解决方案是执行以下操作:
if (array1.Any(c => c == keyInfo.KeyChar)){ ... }
else { ... }