简体   繁体   English

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

[英]C# How do I error check the input ensuring only integers between 1-100 are accepted

I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. 我正在创建一个用于大学作业的程序,任务是创建一个基本上创建随机时间表问题的程序。 I have done that, but need to error check the input to only accept integer inputs between 1-100. 我已经做到了,但是需要对输入进行错误检查,以仅接受1-100之间的整数输入。 I can not find anything online only for like java or for text box using OOP. 我找不到任何在线内容,仅适用于Java或使用OOP的文本框。

Here is my code: 这是我的代码:

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

Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. 首先,我建议您使用TryParse而不是Parse来防止由于无效输入而引起的意外错误。 So, try something like that; 因此,尝试类似的方法;

        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

I'd simply use a loop that will keep asking for input until it matches your requirement: 我只是简单地使用一个循环,它将不断要求输入,直到它符合您的要求:

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

You may also consider granting only N trys to get the input right. 您也可以考虑仅授予N次尝试来获得正确的输入。

A few hints: 一些提示:

  • do not use "magic numbers". 不要使用“幻数”。 Define constants or put numbers into Properties/Settings. 定义常数或将数字放入“属性/设置”。 Name them self-explanatory and document why you chose the value they happen to have. 给他们起个不解的名字,并记录为什么您选择它们​​恰好具有的价值。

  • The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid. 错误消息应该告诉用户预期的有效输入是什么(与他们键入的内容相反),而不仅仅是用户的输入无效。

Whats about this? 怎么了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM