【发布时间】:2013-11-20 19:59:41
【问题描述】:
我的代码要求用户输入一个字母(将 string 转换为 char),但是当按 Enter 键作为输入时,代码会崩溃。
我没有设置任何条件来向用户发送错误消息以在输入时不按 Enter 键并且只输入字母。
这是我正在努力解决的部分:
public static char GetLetter(string prompt)
{
char result;
Console.Write("\n\t" + prompt + ": ");
result = Convert.ToChar(Console.ReadLine());
if(result == '!' || result == '@' || result == '#' || result == '$' || result == '%' )
// we can keep going with all the unwanted characters and numbers
{
Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
result = GetLetter(prompt);
return result;
}
return result;
}
【问题讨论】:
-
我们需要查看实际的错误和输入。
-
Console.ReadKey 可以做到,不是吗?
-
@AlexandreTryHardLeblanc,正是我要去的地方;而且是更正确的做法,但我还是对实际的错误和输入有点好奇。
标签: c# error-handling key enter