0

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;
}
3
  • I used your code to create a fiddle and it runs fine dotnetfiddle.net/0IDn6Y can you post full code and the input example you are trying to give Commented Aug 12, 2018 at 3:15
  • 1
    This method is a bad candidate for recursion in the first place. It would be far more appropriate to use a do or while loop to read the input. Commented Aug 12, 2018 at 3:21
  • I agree with @jmcilhinney Commented Aug 12, 2018 at 3:24

1 Answer 1

1

Your recursive function should be:

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);
        }
        return ReadCoordinates();
    }
    else
    {
        var positionXY = move.ToCharArray();

        return new MissileCoordinates
        {
            PosX = Int32.Parse(positionXY[0].ToString()),
            PosY = Int32.Parse(positionXY[1].ToString())
        };
    }
}

here's the fiddle https://dotnetfiddle.net/kbrP4u

Sign up to request clarification or add additional context in comments.

1 Comment

damn the return keyword. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.