sun*_*wer 5 c# error-handling enter key
我的代码要求用户输入一个字母(转换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;
}
Run Code Online (Sandbox Code Playgroud)
输入时出现错误,因为您得到一个空字符串,因此无法将其转换为字符。
我会建议你这样做:
char result;
string input = Console.ReadLine();
if (char.TryParse(input, out result))
{
//The input is a char - write your code here.
}
//The input is not a char.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1504 次 |
| 最近记录: |