gpt4 book ai didi

C#如何捕捉字母字符

转载 作者:行者123 更新时间:2023-11-30 20:29:35 26 4
gpt4 key购买 nike

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

当前捕获不起作用:

    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");
}

//此捕获在应用程序中无效

    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;

关于我如何挑战这个捕获问题有什么建议吗?

最佳答案

无需捕获任何异常,使用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 是没有意义的。

关于C#如何捕捉字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com