【问题标题】:C# integer validationC# 整数验证
【发布时间】:2014-01-21 17:14:11
【问题描述】:

我已经搜索了 stackoverflow,但没有找到任何可以回答我的问题的内容。不幸的是,将其用作搜索查询并不是一个简单的问题。

我正在使用 c#,并且我有一个菜单,要求用户从 1 到 4 中选择一个选项。我确认选择的值是一个整数,但是每当我输入字母或符号时,我的代码就会中断。如何为此添加验证?我目前的代码如下。

    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.");
            }
        }

【问题讨论】:

    标签: c# validation while-loop


    【解决方案1】:

    改用int.TryParse:

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

    但事实上,您从来没有真正将输入 用作 一个数字,因此没有真正需要解析它。您可以将其保留为字符串:

    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);
    

    此外,虽然这非常清楚且易于准备,但您实际上并不需要 retry 变量。虽然它的工作原理不太明显(出于这个原因我可能会避免它),但您可以像这样构建循环:

    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);
    

    【讨论】:

    • 我试过把它放进去,但没有用。我不确定这些代码是如何工作的,所以我不知道从哪里开始尝试解释错误。恐怕我对此很陌生。
    • @user3158872 这将替换您的Main 方法中folderInfo.GetFiles() 之后的所有内容。您收到什么错误消息?
    • @user3158872 有关此构造的更多信息,另请参阅switch (C# Reference)。
    【解决方案2】:

    将命令行读取改为

    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.");
    }
    

    并在 TryParse if 的 else 部分中为您的用户重复警告消息。

    Int32.TryParse在命令行中的字符无法转换为整数并赋值给out参数mainMenuChoice时返回false。

    【讨论】:

      【解决方案3】:

      在 Int 上使用 TryParse 方法(详情 here)。

      例如:

      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
      }
      

      【讨论】:

        【解决方案4】:
         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!");
        
            }
        

        【讨论】:

          猜你喜欢
          • 2011-09-27
          • 2012-11-02
          • 2012-10-10
          • 1970-01-01
          • 1970-01-01
          • 2013-02-20
          • 2017-01-01
          • 2019-06-02
          • 1970-01-01
          相关资源
          最近更新 更多