Question

I'm building a console based lottery game where user enters his/her choice of numbers. I need to check that the numbers are between 1-39 and user has entered exactly 7 valid numbers. I'd like to do this in a way where user writes them in one line of string in console and the program finds any white space, comma or other non-digit characters and ignores them. The remaining lottery numbers should be stored in integer array which doesn't include any duplicates.

My current version is quite horrible since it gets errors very easily if user writes e.g. 2 spaces between numbers.

Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
        string userRow = Console.ReadLine();
        int[] userLottery = new int[7];
        for(int i = 0; i < userLottery.Length; i++)
            {
                userLottery = userRow.Split(',', '.', ' ').Select(x => int.Parse(x)).ToArray();
                if(userLottery[i] > 7)
                {
                    Array.Resize(ref userLottery, 7);
                }
            }

I'd like to replace my current way in more convenient way where amount of user errors won't affect the program. If the user writes more than one space the error occures.

I have tried to build regular expression to handle these situations but I can't use it to store them in to array.

string userChoice = Console.ReadLine();
        MatchCollection userNumbers = Regex.Matches(userChoice, @"\d+");
        int[] userRow;

        for(int i = 0; i < userNumbers.Count; i++)
        {
            userRow[i] = userNumbers[i].Value;
        }

That says string can't be converted to int[]...

Was it helpful?

Solution 2

Your code doesn't match the instruction to the user. The following does what you tell the user:

  Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
  int[] userLottery = new int[7];

  int i = 0;
  while (i < 7)
  {
      Console.Write("Your choice #{0}: ", i+1);
      string userRow = Console.ReadLine();
      int userNumber;

      if (!Int32.TryParse(userRow, out userNumber) || userNumber < 1 || userNumber > 39)
      {
          Console.WriteLine("Invalid number! Please try again!");
      }
      else
      {
          userLottery[i++] = userNumber;
      }
  }

OTHER TIPS

You could use this LINQ query using String.Split with RemoveEmptyEntries and int.tryParse:

int num = 0;
int[] userLottery = userRow.Trim()
    .Split(new[] { '.', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Where(s => int.TryParse(s.Trim(), out num) && num > 0 && num < 40)
    .Select(s => num)
    .Distinct()
    .ToArray();
if(userLottery.Length != 7)
    Console.WriteLine("Enter 7 valid numbers between 1 and 39");
else
    Console.WriteLine("You have chosen following numbers: " + string.Join(",", userLottery));

Enumerable.Distinct removes duplicates as requested.

Use Regex.Split() for this to handle multiple white spaces.

string[] numbers = Regex.Split(userRow, @"\s+");

\s+ means one or more white spaces. You can use [ ]+ only for space if you want.

You can just parse it with RegEx first and then it should work.

  using System.Text.RegularExpressions;

  Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
  string userRow = Console.ReadLine();
  int[] userLottery = new int[7];

  string[] userEnter = Regex.Split(userRow, " ");

  int n = 0;
  int k = 0;
  for (int i = 0; i < userEnter.Length; i++)
  {
    bool isNumeric = int.TryParse(userEnter[i], out n);
    if(isNumeric == true)
    {
      userLottery[k] = int.Parse(userEnter[i]);
      k++;
    }
  }

Use the following code

        Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");

        string data = Console.ReadLine();

        int[] userLottery = new int[7];
        int i = 0;

        StringBuilder num = new StringBuilder();
        foreach (char item in data)
        {


            if (!Char.IsDigit(item))
            {
                if (num.Length == 0)
                    continue;
                userLottery[i] = int.Parse(num.ToString());
                i++;
                num.Clear();
                continue;
            }

            num.Append(item);
        }

        if(num.Length > 0)
            userLottery[i] = int.Parse(num.ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top