How to validate user input for whether it's an

2019-01-20 11:17发布

It tells me that it can't convert int to bool. Tried TryParse but for some reason the argument list is invalid.

Code:

private void SetNumber(string n)
{
    // if user input is a number then
    if (int.Parse(n)) 
    {
        // if user input is negative
        if (h < 0)
        {
            // assign absolute version of user input
            number = Math.Abs(n); 
        }
        else 
        {
            // else assign user input
            number = n;
        }
    }
    else
    {
        number = 0; // if user input is not an int then set number to 0  
    }
}

10条回答
SAY GOODBYE
2楼-- · 2019-01-20 11:56

There are a lot of problems with this code:

  • Using VB-style line comments (') instead of C# slashes
  • Parse for integer returns an int and not a bool
  • You should use TryParse with an out value
  • h does not seem to be valid at all. Is it a type for n?
  • There are variables that do not seem to be defined in function scope (number) are they defined at class scope?

But try this:

private void SetNumber(string n)
{
    int myInt;
    if (int.TryParse(n, out myInt)) //if user input is a number then
    {
        if (myInt < 0) //if user input is negative
            number = Math.Abs(n); //assign absolute version of user input
        else //else assign user input
            number = n;
    }
    else number = 0; //if user input is not an int then set number to 0
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-20 11:57

Well for one thing the inner if statement has an 'h' instead of an 'n' if(h < 0). But TryParse should work there assuming that 'number' is a class variable.

 private void SetNumber(string n)
    {
        int temp;
        bool success = Int32.TryParse(n, out temp);

        // If conversion successful
        if (success)
        {
            // If user input is negative
            if (temp < 0)
                number = Math.Abs(temp); // Assign absolute version of user input
            else // Assign user input
                number = temp;

        }
        else
        {
            number = 0;
        }

    }
查看更多
太酷不给撩
4楼-- · 2019-01-20 12:01

You were probably very close using TryParse, but I'm guessing you forgot the out keyword on the parameter:

int value;
if (int.TryParse(n, out value))
{

}
查看更多
SAY GOODBYE
5楼-- · 2019-01-20 12:03

You can try with some simple regular expression :

  bool IsNumber(string text)
    {
      Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
      return regex.IsMatch(text);
    }
查看更多
登录 后发表回答