C#如何错误检查输入,确保只接受1-100之间的整数

时间:2017-12-14 12:00:48

标签: c# input

我正在为大学任务创建一个程序,任务是创建一个基本上创建随机时间表问题的程序。我已经这样做了,但是需要错误检查输入以仅接受1-100之间的整数输入。我在网上找不到类似java或使用OOP的文本框。

这是我的代码:

static void help()
    {
        Console.WriteLine("This program is to help children learn how to multiply");
        Console.WriteLine("The program will create times table questions from 1-10");
        Console.WriteLine("The user will be given 10 random questions to complete");
        Console.WriteLine("The user will get a score out of 10 at the end");
        Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
        Console.WriteLine("");
        Console.ReadLine();
        Console.Clear();
    }
    static void Main(string[] args)
    {
        int Random1 = 0;
        int Random2 = 0;
        int Answer;
        int Count = 0;
        int Score = 0;
        int input = 0;
        String choice;

        Console.WriteLine("To begin the Maths test please hit any key");
        Console.WriteLine("If you need any help, just, type help");

        choice = Console.ReadLine();

        if (choice == "help")
        {
            help();
        }

        while (Count != 10)
        {
            Random numbers = new Random();
            Random1 = numbers.Next(0, 11);
            Count = Count + 1;

            Random numbers2 = new Random();
            Random2 = numbers.Next(0, 11);

            Console.WriteLine(Random1 + "x" + Random2 + "=");
            input = int.Parse(Console.ReadLine());

            Answer = Random1 * Random2;

            if (Answer == input)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Correct");
                Score = Score + 1;
                Console.ResetColor();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
                Console.ResetColor();
            }


        }
        if (Score > 5)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Good job you got more than 5 answers correct! With a score of   " + Score + "  out of 10");
            Console.ResetColor();
            Console.ReadLine();
        }
        else if (Score < 5)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("");
            Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + "  out of 10");
            Console.ResetColor();
            Console.ReadLine();
        }
    }
}
}

3 个答案:

答案 0 :(得分:3)

首先,我建议您使用TryParse代替Parse来防止由于输入无效而导致的意外错误。所以,尝试类似的东西;

        Random numbers = new Random();
        Random1 = numbers.Next(0, 11);
        Count = Count + 1;

        Random numbers2 = new Random();
        Random2 = numbers.Next(0, 11);

        Console.WriteLine(Random1 + "x" + Random2 + "=");
        //Modified
        int input = 0;
        while (true)
        {
            if (!int.TryParse(Console.ReadLine(), out input))
            {
                Console.WriteLine("Invalid Input. Please enter a valid integer.");
            }
            else
            {
                if (input >= 1 && input <= 100)
                {
                    break;
                }
                Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
            }
        }
        //Modified

答案 1 :(得分:1)

我只是使用一个循环,一直要求输入直到它 符合您的要求:

int MinVal = 1;    // No magic numbers! You may consider placing them in a config 
int MaxVal = 100;  // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{ 
   // attempt getting input from user
   bool parseOK = int.TryParse(Console.ReadLine(), out input);
   // Exit loop if input is valid. 
   if( parseOK && input >= MinVal && input <= MaxVal ) break; 
   Console.WriteLine( "Errormessage telling user what you expect" );
}

您也可以考虑仅授予N个trys以获得正确的输入。

一些提示:

  • 不要使用“魔术数字”。定义常量或将数字放入属性/设置中。将它们命名为不言自明,并说明您选择它们​​碰巧所具有的价值的原因。

  • 错误消息应该告诉用户预期的有效输入是什么(而不是他们输入的内容),而不仅仅是他们的输入无效。

答案 2 :(得分:-2)

这是怎么回事?

input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
   // valid
}else{
   // invalid
}