C# Exception handling, stop the loop temporarily

Viewed 56

I'm new to C# and i would really need your help with a project.

The idea is to ask the user for 10 numbers between 1-20. The numbers that the user enters are stored in an array. In the next phase a random number i generated and then the program compare all the numbers that the user previously entered with the random number. If one of numbers matches the program write something like "You win!".

My current solution is okay and working but I want a better exception handling than the current one. Here is my problem:

As you can see in my code below I rely on a loop and try/catch to ensure that the user enters a valid number, but after testing several times I discovered that if you enter a valid input, let say the first time but not the second, the unvalid input is still sent to the for-loop and to the next index. I want to ensure that the user enters a valid number and if not the for-loop would temporarily "pause" until the next VALID number is entered.

bool start = true; //Create a loop.
            {
                while (start == true)
                {
                    try
                    {
                        for (int x = 0; x < vektor.Length; x++) //To fill my array.
                        {
                            Console.WriteLine("Enter a number between 1 and 20:");
                            vektor[x] = int.Parse(Console.ReadLine());
                            start = false;
                        }
                        
                    }

                    catch
                    {
                        Console.WriteLine("Error, you need to enter a number!");
                    }
                }

                
            }
1 Answers

Make a method that asks the user a question and doesn't give an answer until it's valid:

public int Ask(string question, int lower, int upper){


    while(true)
    {
      Console.WriteLine(question);
      string input = Console.ReadLine();
      bool valid = int.TryParse(input, out int inputInt); //valid is true if it was a number
      
      valid = valid && inputInt >= lower && inputInt <= upper; //but also test was it in range?

      if(valid)
        return inputInt;  //if not valid, repeat the question because the loop is infinite
    }

}

valid will be true if the user enters a number, but if they entered 40 for a 1 to 20 range, then the second validity assessment is:

valid = true /*it was a number*/ && true /*40 is >= 1*/ && false /*40 is not <= 20*/

So valid becomes false. We can only escape the Ask() method, returning the valid number if valid is true, otherwise the loop goes round again

--

Now you can have a list of numbers, say you want 10, we can loop and add numbers to a list until we get 10:

List<int> numbers = new List<int>();

while(numbers.Count < 10)
{
  int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
  numbers.Add(validNumber);
}

You can do this as an array if you like:

int[] numbers = new int[10];

for(int x = 0; x<numbers.length; x++)
{
  int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
  numbers[x] = validNumber;
}

Because you know that the Ask method will never return unless the input is valid, so the loop "pauses"

Related