This code snippet reads the input from console and returns an object. If there are any errors it calls itself again.
I have validation rule to check if input values are not letters. And my Validator is returning that error and calling this function again to take correct input.
The problem with below code is that:
- When I give incorrect input, let's say "abc".
- Validator returns error and print that out on console and asks for new input.
- Now, when I submit the correct input, say 12, it throws a
FormatException during parsing the char Array. line :
Int32.Parse(positionXY[0].ToString())
How can I fix it ?
public MissileCoordinates ReadCoordinates()
{
PrintLine($"Enter Coordinates", ConsoleColor.White);
var move = Console.ReadLine();
List<string> errors = constraintValidator.ValidateMissile(move).ToList();
if (errors.Any())
{
foreach (var error in errors)
{
PrintLine(error, ConsoleColor.White);
}
ReadCoordinates();
}
else
{
var positionXY = move.ToCharArray();
return new MissileCoordinates
{
PosX = Int32.Parse(positionXY[0].ToString()),
PosY = Int32.Parse(positionXY[1].ToString())
};
}
return null;
}
doorwhileloop to read the input.