【问题标题】:C# How to catch alphabetical charactersC#如何捕捉字母字符
【发布时间】:2017-08-30 13:56:54
【问题描述】:

我目前正在开发一个高度转换计算器,将英尺和英寸转换为厘米,并希望创建一个“catch”,当用户输入字母字符而不是数字字符时会产生错误消息,甚至可能是一个将地址是用户输入无效(例如输入 5' 111' 而不是 5' 11')。

当前的 catch 不起作用:

    Console.Clear();
    Console.WriteLine("Convert your height into Centimeters!");
    Console.WriteLine("Please give your height in the form of Feet and Inches, for example: 5'10\"");
    //user enters 5'10"
    heightString = Console.ReadLine();
    //heightString = "5'10""
    heightString = heightString.Remove(heightString.Length - 1);
    //heightString = "5'10"
    posOfInch = heightString.IndexOf("'");
    //posOfInch = 1

            try
            {
            }

            catch ()
            {
                throw new ("Generic Error Message");                    
            }

//这个catch在应用内无效

    feet = Convert.ToInt16(heightString.Remove(posOfInch));
    //feet = 5
    inches = Convert.ToInt16(heightString.Substring(posOfInch + 1));
    //inches = 10

    inches = (feet * 12) + inches;
    centimetres = (inches * 2.54);

    Console.WriteLine("Your height is " + centimetres + "cm");
    //Console.WriteLine("Please give your height measurement in inches : ");
    //calculating = int.Parse(Console.ReadLine());
    //inches(calculating);
    Console.ReadKey();
    return true;

关于如何挑战这个捕获问题的任何建议?

【问题讨论】:

  • 没有演员表,所以你为什么要处理InvalidCastException
  • try 块中没有导致异常的代码 - 您是在问需要在其中放入什么来验证您的字符串吗?
  • 抱歉,是的。我要求澄清我可以在 codeBlock 中放置的内容,以确保在提供字母输入时显示错误消息,而不是数字英尺和英寸值?
  • 有两种方法可以做你想做的事:使用正则表达式或创建解析器 (en.wikipedia.org/wiki/Recursive_descent_parser)。研究一下。

标签: c# try-catch


【解决方案1】:

不需要捕获任何异常,使用TryParse

string heightString = "5'10";

short feet, inches;
bool validFormat = false;
int index = heightString.IndexOf("'", StringComparison.Ordinal);

if (index >= 0)
    validFormat = short.TryParse(heightString.Remove(index), out feet)
               && short.TryParse(heightString.Substring(index + 1), out inches);

顺便说一句,既然你不施放任何地方,捕捉InvalidCastException 是没有意义的。

【讨论】:

  • 抱歉,示例输入 - "5'10\""(请注意结尾的 " - 英寸)格式无效
  • @DmitryBychenko:嗯,这是有效的输入吗? OP已经提到这是无效的,这也是上面代码的结果。-
  • @Tim Schmelter:似乎是因为问题Console.WriteLine("Please give your height in the form of Feet and Inches, for example: 5'10\""); 中的代码提供了这个示例
  • @DmitryBychenko:不错,我必须承认我不熟悉英尺和英寸的格式。所以也许首先简单地修剪就足够了:heightString=heightString.Trim('"');
【解决方案2】:

因为您还需要进行输入验证(不仅仅是转换),所以我建议使用正则表达式。例如:

\d+'\d{2}'

将只接受 1 位或多位数字的输入,后跟一个引号,然后是其他 2 位数字和最后一个引号(只是一个示例,您可能会找到一个更有选择性的)。

此外,如果您想提取值进行转换并将它们存储为整数,您可以使用分组并提取值,只需在要捕获的输入周围加上括号即可。

参考看看这个:https://www.codeproject.com/articles/93804/using-regular-expressions-in-c-net

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多