Home > Back-end >  I need to see if there is a way to end this loop when a criteria is met else where
I need to see if there is a way to end this loop when a criteria is met else where

Time:10-24

I am making a quiz for my first homework of college and need to validate the users input and make sure that it is a number from 1 to 100 and not a character or blank, I want this process to repeat until it is valid then carry on with the rest of the program.

using System;
using System.Linq;

namespace _17th_Nov_assignment_program
{
    class Program
    {
        static void Main(string[] args)
        {
            int end = 0;

            Console.WriteLine("Welcome to the 10 question multiplication quiz !\n");
            Console.WriteLine("Answer each question and find out your score at the end !\n");

            //Question 1
            {
                Console.WriteLine("Question 1.");
                Questions();
                {
                    do
                    {
                        Validate();
                    } while (end == 0);
                }

            }

            Console.ReadKey();
        }

        private static string Questions()
        {
            int Calc = 0;

            // This creates Random and generates value one and two randomly from 1 to 10.
            Random r = new Random();
            int Value_One = r.Next(1, 10);
            int Value_Two = r.Next(1, 10);

            //Console.WriteLine(Value_One.ToString());
            //Console.WriteLine(Value_Two.ToString());

            // This multiplies them together
            int Multiply = Value_One * Value_Two;
            //Console.WriteLine(Multiply);

            Calc = Multiply;

            // This prints the multiplication question
            Console.WriteLine("Please calculate: "   Value_One   " * "   Value_Two   "\n");
            return Calc.ToString();
        }

        private static string Validate()
        {
            int PlaceHolder = 0;

            Console.WriteLine("Please enter your answer below\n");
            string usrAns = Console.ReadLine();
            int Checker1 = 100;
            int Checker2 = 1;

            {
                if (usrAns.All(usrAns => Char.IsLetter(usrAns)))
                {
                    PlaceHolder = 0;
                    Console.WriteLine("Please enter a valid number!");

                }
                else if (usrAns == string.Empty)
                {
                    Console.WriteLine("Please enter a valid number!");

                }
                else if (Int32.Parse(usrAns) > Checker1)
                {
                    Console.WriteLine("Please eneter a valid number!");
                    PlaceHolder = 0;
                }
                else if (Int32.Parse(usrAns) < Checker2)
                {
                    Console.WriteLine("Please eneter a valid number!");
                    PlaceHolder = 0;
                }
                else
                {
                    Console.WriteLine("Valid answer, now lets see if it's correct! \n");
                    PlaceHolder  ;
                }
            }

            {
                return usrAns.ToString();
            }
        }
    }
}

CodePudding user response:

If i understood you correctly you want to create a multiply game which randomly multiplies 2 numbers and the user have to input the result correctly.

My suggestion would be to not work with string as returns for your methods.

E.g. the first method could create the random values and print the text to the console and return the multiply result directly:

private static int CreateRandomMultiplyResult()
    {
        Random random = new Random();
        int value1 = random.Next(1, 10);
        int value2 = random.Next(1, 10);

        // with $ we 'mark' the string for string interpolation that allows us to directly pass variables where we want them wiht {}
        Console.WriteLine($"Please calculate: {value1} * {value2}");
        // does the same as above
        //Console.WriteLine(string.Format("Please calculate: {0} * {1}", value1, value2));

        return value1 * value2;
    }

You can store the result of this call as your expectedResult.

Then you can read the user input (for that i created a method which only prints the info for the user and reads his input and directly return the input). In this case we need the string return because it is the user intput:

private static string ReadUserInput()
    {
        Console.WriteLine("Please enter your answer:");
        return Console.ReadLine();
    }

Last i created a method which should validate the value from the user. Therefore i accepted 2 parameters. First is the input as string and second the expected result. I just checked if the input is a valid integer and if this is the case then if it is equal to the expected result. Because i don't care if the input is below 1 or higher then 100, this values will anyways be invalid because of the random limited to 1 - 10.

private static bool ValidateValue(string userInput, int result)
    {
        if (!int.TryParse(userInput, out int parsedInput))
        {
            Console.WriteLine("Please enter a number!");
            return false;
        }

        return parsedInput == result;
    }

Of course you can also check the parsed value for < 100 and > 0 if you want / have to.

Lastly my main method. I only have one created question and if the answer is correct my program closes.

static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        int expectedResult = CreateRandomMultiplyResult();

        bool valid = false;
        do
        {
            string userInput = ReadUserInput();
            valid = ValidateValue(userInput, expectedResult);
        } while (!valid);

        Console.Read();
    }

I hope this helps you feel free to ask if i should explain anything.

CodePudding user response:

Despite you won't see it as helpful at first, slice your functions into such form they do one thing, and they do it correctly. Take for example system Math.Sqrt, it works fine no matter if you write web app, GUI app, console app, because it does one job and not try to for example print its output.

Your Validate function on the other hand does everything, prints to the terminal, reads from the terminal, validates, etc (and what worse the name miguides the reader of the code).

Make it clean, Validate should only validate the data -- pass the input, retun true/false depending if the data was valid or not, return the error message. That's it.

After you do this, the flow of the logic should be apparent.

  •  Tags:  
  • c#
  • Related