仅输入数字的验证规则

时间:2015-11-24 09:19:19

标签: c#

您好我已经创建了一个带有验证规则的程序但是在显示userChoice的选项屏幕上,如果您键入一个字母而不是一个数字,程序会崩溃,然后按回车键。是否有一个验证规则,只能输入一个数字而不是一个字母。我已经输入了1到3之间的数字验证规则。

    int userChoice, number;

    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");
        string userChoiceSTR = Console.ReadLine();

        if (!string.IsNullOrEmpty(userChoiceSTR))
        {
            userChoice = Convert.ToInt16(userChoiceSTR);  
            try
            {
                Options();
            }
            catch
            {
                Console.WriteLine("Did not put any value. Please Select a menu: ");
                Main_Menu();
            }
        }
        else
        {
            Console.WriteLine("Did not put any value. Please Select a menu: ");
            Main_Menu();
        }

        if (userChoiceSTR != "1" && userChoiceSTR != "2" && userChoiceSTR != "3")
        {
            Console.WriteLine("You need to provide a value between 1 and 3");
            Main_Menu();
        }


    }

    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 
        }

0 个答案:

没有答案