【发布时间】: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)。研究一下。