C# for beginners -Consecutive Numbers

Hi, I have been learning C# recently and one of the problems I was given to solve was as follows:

Read in numbers until the same number is typed X times in succession. Have the user specify the value of X.

Seemed simple enough but as a beginner in the language I have still been grappling with basic syntax and learning where some of the base classes in the .NET framework provide much of the functionality one needs in developing apps.

That aside I started building my basic console application and class to solve the problem. While I was trying to figure out how to identify how many numbers in succession had been typed I turned to our trusty friend Google to search for some possible code snippets that may have helped me solve the problem.

While there seemed to be lots of possible solutions from programmers no doubt far more skilled than myself in the search results, most of them I couldn’t get to work with my code or were far too cryptic for my beginner status. All sorts of sub-string manipulation techniques and  use of things like regular expressions (regex), which for my level seemed more cryptic than the code I was trying to write. I did find one particular regex example that tested if three consecutive characters had been typed but I couldn’t figure out how to modify a regular expression based on variable X that the user had input, so it didn’t seem useful to me in what I was trying to solve. To be fair it would seem that regex is very adept at solving advanced pattern recognition problems, but beyond my expertise at this point.

Scratching my head I thought there had to be an easier way to solve this, and went back to basics. All I needed to do was the following:

  1. Check the input entered so far in the console against X times the last number input.
  2. As I already knew the value of X, I therefore only had to check the last X characters of the input already entered (a sub-string of the entire input).
  3. Compare X times the last character entered against the last X characters of the entire input stream. Match being true or false.
  4. If true execute whatever needed to be done, if false loop back through until X consecutive numbers had been input.

While I have added additional code for error checking such as whether the user has actually entered a number, I figured I would share this code with the masses. Believe me I doubt it is anything exciting to competent C# developer, but no doubt may help beginners like me trying to solve something similar.

I would also be interested in feedback from more experienced developers on alternatives that may be more efficient, or expand on the capability of what I have written. No doubt there are probably more elegant ways.

Anyway here is the code for all to see:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CountNumbers
{
    class Program
    {
        static void Main(string[] args)
        {

            int consecutiveNumber = 0;
            Console.WriteLine(@"Please enter the number of times in succession a number can be typed into the console before the program will finish?");
            consecutiveNumber = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(@"Start typing numbers into the console. Keep typing until you type the same number " + consecutiveNumber +
                 " times in a row:");
            string userValue = "";
            int userValueIsNumber = 0;
            string lastUserValue=null;
            bool hasRepeatingNumbers = false;
            while (hasRepeatingNumbers != true)
                {
                if (userValue.Length < consecutiveNumber)
                {
                    //Next we test to see if the value read at the console is actually a whole number and not 
                    //another character. If it is not a valid number then we prompt the user to type numbers only.
                    if (int.TryParse(lastUserValue = Console.ReadKey().KeyChar.ToString(),out userValueIsNumber))
                    {
                        userValue = userValue + lastUserValue;
                    }
                    else
                    {
                        Console.Clear();
                        Console.WriteLine("You must type only numbers");
                        Console.WriteLine(@"Start typing numbers into the console. Keep typing until you type the same number " + consecutiveNumber +
                 " times in a row:");
                        Console.Write(userValue);
                    }
                    
                }
                else
                {
                    if (int.TryParse(lastUserValue = Console.ReadKey().KeyChar.ToString(), out userValueIsNumber))
                    {
                        userValue = userValue + lastUserValue;
                        string requiredNumberOfCharacters = userValue.Substring(userValue.Length - consecutiveNumber);
                        string testOfCharacters = new string(Convert.ToChar(lastUserValue), consecutiveNumber);
                        if (requiredNumberOfCharacters == testOfCharacters)
                        {
                            hasRepeatingNumbers = true;
                        }
                    }
                    else
                    {
                        Console.Clear();
                        Console.WriteLine("You must type only numbers");
                        Console.WriteLine(@"Start typing numbers into the console. Keep typing until you type the same number " + consecutiveNumber +
                 " times in a row:");
                        Console.Write(userValue);
                    }                    
                }
            }
            Console.WriteLine();
            Console.WriteLine(@"The number " + lastUserValue + " was printed " + consecutiveNumber + " times in succession.");
            Console.ReadKey();
        }
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s