简体   繁体   中英

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. I can not find anything online only for like java or for text box using 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. 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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