Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
    }
}
like image 250
Namespace Avatar asked Mar 22 '11 17:03

Namespace


People also ask

How do you validate if an input is an integer?

Approach used below is as follows − Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int. Print the resultant output.

How do you check if it is an integer?

isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you check if input string is a number?

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you input an integer as a user?

To use them as integers you will need to convert the user input into an integer using the int() function. e.g. age=int(input("What is your age?")) This line of code would work fine as long as the user enters an integer.


1 Answers

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

}
like image 94
Justin Avatar answered Oct 20 '22 02:10

Justin