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
}
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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With