none
How can I validate my user input so that the console application doesn't crash. RRS feed

  • Question

  • I'm a beginner at c# and any help will be appreciated.

    Essentially the user is asked to input the SecurityCode which has been {get, set,} in the Cars class. The information for this Cars class is stored in a txt file and loaded into the console app.

    static List<Car> Cars= new List<Car>(); //list containing the cars

    The code I used to input the cars security code and find it's index:

    Console.WriteLine("\nPlease enter the SecurityCode of the car you wish to delete\n"); var securityCode = int.Parse(Console.ReadLine()); Car delete = Cars.Find(cr => cr.SecurityCode == securityCode);

    int index = Cars.IndexOf(delete);
                            Cars.RemoveAt(index); //Deletes the car
                            Cars.CarsNumber--; //Decrements the car count

    This all works fine.

    How can I validate this so that the console won't crash when the user inputs the wrong SecurityCode?


    Umar Arif

    Saturday, April 27, 2019 3:39 PM

Answers

  • You could use Int32.TryParse instead of Int32.Parse and check for the right input in an if-condition:
    Console.WriteLine("\nPlease enter the SecurityCode of the car you wish to delete\n");
    if (Int32.TryParse(Console.ReadLine(), out int securityCode))
    {
    	var index = Cars.IndexOf(Cars.FirstOrDefault(cr => cr.SecurityCode == securityCode));
    	if (index >= 0) Cars.RemoveAt(index);
    }
    else
    	Console.WriteLine("Wrong input.");
    wizend
    Saturday, April 27, 2019 6:53 PM

All replies

  • You could use Int32.TryParse instead of Int32.Parse and check for the right input in an if-condition:
    Console.WriteLine("\nPlease enter the SecurityCode of the car you wish to delete\n");
    if (Int32.TryParse(Console.ReadLine(), out int securityCode))
    {
    	var index = Cars.IndexOf(Cars.FirstOrDefault(cr => cr.SecurityCode == securityCode));
    	if (index >= 0) Cars.RemoveAt(index);
    }
    else
    	Console.WriteLine("Wrong input.");
    wizend
    Saturday, April 27, 2019 6:53 PM
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, April 29, 2019 5:09 AM
    Moderator