TBK
TBK

Reputation: 51

Check if user input is a number

I want to check if user's input is a number. If yes I want the function to keep running else want to alert him and run it again.

Console.WriteLine(String.Concat("choose your action" ,Environment.NewLine ,
                                "1.Deposit", Environment.NewLine,
                                "2.Withdraw", Environment.NewLine,
                                "3.CheckAccount"));
string c = Console.ReadLine();
int value = Convert.ToInt32(c);

if (value==char.IsLetterOrDigit(value)) //<----- no good why?
{
    switch (value)
    {
        case 1:
            Deposit();
            return;
        case 2:
            Withdraw();
            return;
        case 3:
            CheckAccount();
            return;
    }
}

Upvotes: 2

Views: 55791

Answers (3)

Rishabh Sen
Rishabh Sen

Reputation: 1

    Write:
`string chooseNum = Console.ReadLine();
int val;\\in which the value will pass
if (!checkNum )
{
    Console.WriteLine("Its not a Number");
}*\\ We Will Directly get out of it if its not a Number*
else
{ 
if (val >= 1 && val <=3)
        switch (val)
    {
        case 1:
            Deposit();
            return;
        case 2:
            Withdraw();
            return;
        case 3:
            CheckAccount();
            return;
    }
}
    else
        Console.WriteLine("Number Must be b/w 1 and 3");
}
 `

Upvotes: 0

alpha
alpha

Reputation: 17

int value = Convert.ToInt32(c); this is going to fail if c is not a string consisting of integers only. use try catch to handle this situation.

Upvotes: 1

e_ne
e_ne

Reputation: 8469

Just use:

string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value)) { /*Operate*/ }

EDIT: to adapt the code to the author's comment:

if (int.TryParse(c, out value) && value >= 1 && value <= 3) { /*Operate*/ }

Upvotes: 17

Related Questions