Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program crashes when no value is entered

Tags:

c#

I have created a program and have come across a problem. when I debug the program and don't enter a value e.g. a number and press the enter button a few times, the program eventually crashes. I am wondering is there a validation rule that could be put in place so the program doesn't crash when no value has been entered.

int userChoice;

static void Main(string[] args)
{
    new Program().Welcome();
}


public void Welcome()
{

    Console.WriteLine("                       HELLO");
    Console.ReadLine();
    Main_Menu();

}

private void Main_Menu()
{

    Console.WriteLine("1). Welcome");
    Console.WriteLine("2). Help Facilities");
    Console.WriteLine("3). Exit");

    userChoice = Convert.ToInt16(Console.ReadLine());
    Options();
}

private void Options()
{

    if (userChoice == 1)
    {

        Console.Clear();
        Console.WriteLine("Welcome.....................");
        Console.ReadLine();


    }
    if (userChoice == 2)
    {
        Console.Clear();
        Console.WriteLine("Help.........................");
        Console.ReadLine();
    }

    if (userChoice == 3)
    {
        //if user selects option 3 the program will exit 

    }
like image 314
Naz Avatar asked Dec 21 '25 13:12

Naz


1 Answers

Don't just parse, use try parse to validate if its a number or not.

Here is some shorthand's for integer types (whole numbers)

  • long = Int64
  • int = Int32
  • short = Int16
  • byte = (what whould be Int8 if it existed)

So just use the shorthand's they are a little bit more readable as they are more distinct.

int t;
if(int.TryParse(Console.ReadKey(),out t){
//Do work with the number t
}
else{
//Handle a non numerical input
}
like image 91
Thomas Andreè Wang Avatar answered Dec 24 '25 05:12

Thomas Andreè Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!