3

I have searched stackoverflow and haven't found anything that answers my question. Unfortunately it is not an easy question to word as a search query.

I'm using c# and I have a menu that asks the user to pick an option from 1 - 4. I am validation that the value picked is an integer, but my code breaks whenever I enter a letter or symbol. How do I add the validation for this to? My code currently is as follows.

    static void Main(string[] args)
    {
        DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
        FileInfo[] files = folderInfo.GetFiles();
        int mainMenuChoice=0;
        while ( mainMenuChoice != 1 || mainMenuChoice!= 2 || mainMenuChoice!= 3 || mainMenuChoice!= 4)
        {
            Console.WriteLine("What would you like to do?");
            Console.WriteLine("1. Full File Listing.");
            Console.WriteLine("2. Filtered File Listing.");
            Console.WriteLine("3. FolderStatistics.");
            Console.WriteLine("4. Quit.");

            mainMenuChoice = int.Parse(Console.ReadLine());
            if (mainMenuChoice == 1)
            {
                Option1();
            }
            if (mainMenuChoice == 2)
            {
                Option2();
            }
            if (mainMenuChoice == 3)
            {
                Option3();
            }
            if (mainMenuChoice == 4)
            {
            }
            else
            {
                Console.WriteLine("you didnt enter a valid input! try again.");
            }
        }
Flexo
  • 87,323
  • 22
  • 191
  • 272

4 Answers4

6

Change the reading from the command line to

if(Int32.TryParse(Console.ReadLine(), out mainMenuChoice))
{
    if (mainMenuChoice == 1)
        Option1();
    else if (mainMenuChoice == 2)
        Option2();
    else if (mainMenuChoice == 3)
        Option3();
    else if (mainMenuChoice == 4)
        Option4();
    else
        Console.WriteLine("you didnt enter a valid input! try again.");
}
else
{
    Console.WriteLine("you didnt enter a valid input! try again.");
}

and repeat the warning message for your user in the else part of the TryParse if.

Int32.TryParse return false when the characters on the command line cannot be converted to an integer and assigned to the out parameter mainMenuChoice.

Steve
  • 213,761
  • 22
  • 232
  • 286
4

Use int.TryParse instead:

if (!int.TryParse(Console.ReadLine(), out mainMenuChoice))
{
    Console.WriteLine("That's not a number!");
}
...

But in fact, you're never actually using the input as a number, so there's no real need to parse it. You could just leave it as a string:

bool retry;
do
{
    retry = false;
    Console.WriteLine("What would you like to do?");
    Console.WriteLine("1. Full File Listing.");
    Console.WriteLine("2. Filtered File Listing.");
    Console.WriteLine("3. FolderStatistics.");
    Console.WriteLine("4. Quit.");

    string mainMenuChoice = Console.ReadLine();
    switch(mainMenuChoice)
    {
        case "1":
            Option1();
            break;
        case "2":
            Option2();
            break;
        case "3":
            Option3();
            break;
        case "4":
            break;
        default:
            Console.WriteLine("You didn't enter a valid input! Try again.");
            retry = true;
            break;
    }
} while(retry);

Also, although this is pretty clear and easy to ready, you don't actually need the retry variable. Although it's a lot less obvious how this works (and I would probably avoid it for that reason), you can structure your loop like this:

do
{
    Console.WriteLine("What would you like to do?");
    Console.WriteLine("1. Full File Listing.");
    Console.WriteLine("2. Filtered File Listing.");
    Console.WriteLine("3. FolderStatistics.");
    Console.WriteLine("4. Quit.");

    string mainMenuChoice = Console.ReadLine();
    switch(mainMenuChoice)
    {
        // same as above
        default:
            Console.WriteLine("You didn't enter a valid input! Try again.");
            continue; // goes back to beginning of the loop
    }
    break; // exits the loop
} while(true);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    i have tried putting that in, but it did not work. im not sure how any of that code works, so i wouldnt know where to begin trying to explain the error. i am quite new to this im afraid. –  Jan 03 '14 at 22:40
  • @user3158872 This would replace everything after `folderInfo.GetFiles()` in your `Main` method. What error message do you get? – p.s.w.g Jan 03 '14 at 22:42
  • @user3158872 See also [switch (C# Reference)](http://msdn.microsoft.com/en-us/library/06tc147t.aspx) for more information on this construct. – p.s.w.g Jan 03 '14 at 22:49
0
 while(true)
    {
        int menuChoice;
        string userInput = Console.Readline();
        if(Int32.TryParse(userInput, out menuChoice))
        {
            if(menuChoice >= 1 && menuChoice <= 4)
               RunCommand(menuChoice);
            else
               Console.WriteLine("Enter a number between 1-4");
        }
        else
            Console.WriteLine("A number between 1-4 is required!");

    }
Odrai
  • 2,163
  • 2
  • 31
  • 62
0

Use the TryParse method on Int (details here).

For example:

int menuChoice;
if(!int.TryParse(Console.Readline(),out menuChoice){
   Console.WriteLine("The menu choice you made was invalid.");
} else {
   //do the rest of your code here
}
melodiouscode
  • 2,105
  • 1
  • 20
  • 41