我在 C# 中设计了一个输入验证循环,我希望它能够检查正确的输入格式。我不确定,但我认为我设计的循环不是检查输入的类型,而是检查输入的字符。我知道我可以使用 try-catch block ,但你不应该只在特殊情况下使用异常吗?这不是特殊情况,因为我预计用户会输入错误的值。
问题:
有没有一种方法可以重新设计此循环,使其也检查有效输入 type?
代码:
do
{
Console.Write("Do you wish to enter another complex number?: (Y or N)");
response = char.Parse(Console.ReadLine());
response = char.ToUpper(response);
if (response != 'Y' && response != 'N')
Console.WriteLine("You must respond Y or N!");
} while (response != 'Y' && response != 'N');
最佳答案
Reads the next line of characters from the standard input stream.
因此您的数据类型为 System.String
.
您唯一可以做的其他检查是检查返回的字符串的长度是否为 1,这样您就知道您输入了正确的格式。您实际上并不需要 char.Parse
,因为字符串的元素是 char
类型。
关于c# - 验证用户输入和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1853712/