Xamari android string validate to int variable

Help atm i on mobile so cant post code so heres the code i need help with.
Doing a maths app. Random number generates and anather one. Display as text and save answear to variable. If user is correct continue else fail. How to do that sort of validation when userinput is text and the thing its supposed to be equal to is an int.

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    Since the following code has limited the number randomNumber1 and number randomNumber2 to the range of [1, 12) :

       int randomNumber1 = random.Next(1, 12);
       int randomNumber2 = random.Next(1, 12);
    

    So ,we just need to verify if the input number string is a number string .
    The method is as follows:

        bool isNumberic(string message, out int result)
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            result = -1;
            if (rex.IsMatch(message))
            {
                result = int.Parse(message);
                return true;
            }
            else
                return false;
        }
    

    Then we could call the isNumberic method like this

            int randomNumber1 = random.Next(1, 12);
            int randomNumber2 = random.Next(1, 12);
            int result = randomNumber1 + randomNumber2;
    
            string str = UserInput.Text;
            if (isNumberic(str, out int temp))
            {
                if (temp == result)
                {
    
                }
                else
                {
    
                }
            }
    
Sign In or Register to comment.