Reputation: 35
I'm currently working on a height conversion calculator, converting feet and inches to centimetres and want to create a "catch" that will produce an error message when the user inputs alphabetical characters rather than numerical characters, even potentially a catch that will address is the user input is invalid (e.g. entering 5' 111' rather than 5' 11').
The current catch doesn't work:
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");
}
// this catch is invalid within the application
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;
Any advice on how I can challenge this catch issue?
Upvotes: 2
Views: 232
Reputation: 962
Because you also need to do input validation (not just the conversion) I recommend using a regular expression. For instance:
\d+'\d{2}'
will only accept inputs with 1 or more digit, followed by a quote, in turn followed by other 2 digits and a final quote (just an example, you may find a more selective one).
Moreover if you want to extract the values to the convert them and store them as integers, you can use grouping and extract the values, just by putting parentheses around the input you want to capture.
For reference check this out: https://www.codeproject.com/articles/93804/using-regular-expressions-in-c-net
Upvotes: 0
Reputation: 460168
No need to catch any exceptions, use 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);
By the way, since you don't cast anywhere, catching an InvalidCastException
is pointless.
Upvotes: 4