Namespace
Namespace

Reputation: 91

How to validate user input for whether it's an integer?

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  
    }
}

Upvotes: 9

Views: 119783

Answers (10)

Vino
Vino

Reputation: 1

I did this in the simplest way I knew how.

 static void Main(string[] args)
    {
        string a, b;
        int f1, f2, x, y;
        Console.WriteLine("Enter two inputs");
        a = Convert.ToString(Console.ReadLine());
        b = Console.ReadLine();
        f1 = find(a);   
        f2 = find(b);   

        if (f1 == 0 && f2 == 0)
        {
            x = Convert.ToInt32(a);
            y = Convert.ToInt32(b);
            Console.WriteLine("Two inputs r number \n so tha additon of these text box is= " + (x + y).ToString());
        }
        else
            Console.WriteLine("One or tho inputs r string \n so tha concadination of these text box is = " + (a + b));
        Console.ReadKey();
    
    }
        static int find(string s)
        {
        string s1 = "";
        int f;
         for (int i = 0; i < s.Length; i++)
            for (int j = 0; j <= 9; j++)
            {
                string c = j.ToString();
                if (c[0] == s[i])
                {
                    s1 += c[0];
                }
            }
        
        if (s==s1)
            f= 0;
        else
            f= 1;

        return f;
    }

Upvotes: 0

Yan Zhao
Yan Zhao

Reputation: 185

You can try with some simple regular expression :

  bool IsNumber(string text)
    {
      Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
      return regex.IsMatch(text);
    }

Upvotes: 4

Tib
Tib

Reputation: 272

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;
        }

    }

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81557

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
}

Upvotes: 2

Shakakai
Shakakai

Reputation: 3564

int.Parse will convert a string to an integer. Current you have it within an if statement, so its treating the returned value of int.Parse as a bool, which its not.

Something like this will work:

private void SetNumber(string n)
{
    int num = 0;
    try{
        num = int.Parse(n);
        number = Math.Abs(num);
    }catch(Exception e){
        number = 0;
    }   
}

Upvotes: 0

Mikael &#214;stberg
Mikael &#214;stberg

Reputation: 17176

Just use this:

int i;
bool success = int.TryParse(n, out i);

if the parse was successful, success is true.

If that case i contain the number.

You probably got the out argument modifier wrong before. It has the out modifier to indicate that it is a value that gets initialized within the method called.

Upvotes: 8

Swaff
Swaff

Reputation: 13621

int.Parse will give you back an integer rather than a boolean.

You could use int.TryParse as you suggested.

int parsedValue;
if(int.TryParse(n, out parsedValue))
{
}

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82375

You could try something like below using int.TryParse..

        private void SetNumber(string n)
        {
            int parsed = -1;
            if (int.TryParse(n, out parsed)) //if user input is a number then
            ...

The reason there are complaints that it cannot convert an int to a bool is because the return type of int.Parse() is an int and not a bool and in c# conditionals need to evaluate bool values.

Upvotes: 1

Bala R
Bala R

Reputation: 109027

    private void SetNumber(string n)
    {
        int nVal = 0;

        if (int.TryParse(n, out nVal))
        {
            if (nVal < 0)
                number = Math.Abs(nVal);
            else
                number = nVal;
        }
        else
            number = 0;
    }

Upvotes: 3

Justin
Justin

Reputation: 6711

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))
{

}

Upvotes: 18

Related Questions