Paul Skinner
Paul Skinner

Reputation: 43

C# Checking users input before placing it into an array

I am wanting the user to input 10 numbers between 10 and 100, they must be unique otherwise it will ask you for a new number. I was able to get the array to work and accept 10 numbers but it will not check it against the other numbers or be between my values. Below this code is a code that I wrote that works but is not a loop. Any help is appreciated.

    int a;
      int[] arr = new int[10]; // The size of the array is 10

      // Here the values are accepted from the user
      for (a = 0; a <= 9; a++)
      {
      Console.Write("\nEnter your number:\t");
      //Here is were all the storing is done
      arr[a] = Convert.ToInt32(Console.ReadLine());
      //Here is my check values for the inputted numbers
      if (arr[a] < 10 || arr[a] > 100)  // I tried using brackets and && nothing worked
      {
      // If they do not meet the correct information
      Console.WriteLine
      ("You did not enter a valid number.");
      --arr[a];

      }
      else
      {
      //When they do meet the correct values
      Console.WriteLine("Thanks for entering the number " + arr[a]);
      }
      }

      Console.WriteLine("\n");
      //Here the inputted values are printed out
      for (a = 0; a < 10; a++)
      {
      Console.WriteLine("You entered the number {0}", arr[a]);
      }
      Console.ReadLine();

The code I wrote that works is not a loop. I am trying to do this exact code with less writing and as a Loop.

            Console.WriteLine("Please enter 10 numbers between 10 and 100. They cannot be identical.");
            Retrypoint1:
            int a = int.Parse(Console.ReadLine());
            if ((a > 10) && (a < 100));

            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100.\r\n Please try again.");
                goto Retrypoint1;
            }
            Retrypoint2:
            int b = int.Parse(Console.ReadLine());
            if ((b > 10) && (b < 100) && (b != a)) ;
            else
            {

                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint2;

            }
            Retrypoint3:
            int c = int.Parse(Console.ReadLine());
            if ((c > 10) && (c < 100) && (c != a) && (c != b)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint3;
            }
            Retrypoint4:
            int d = int.Parse(Console.ReadLine());
            if ((d > 10) && (d < 100) && (d != a) && (c != b) && (d != c)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint4;
            }
            Retrypoint5:
            int e = int.Parse(Console.ReadLine());
            if ((e > 10) && (e < 100) && (e != a) && (e != b) && (e != c) && (e != d)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint5;
            }
            Retrypoint6:
            int f = int.Parse(Console.ReadLine());
            if ((f > 10) && (f < 100) && (f != a) && (f != b) && (f != c) && (f != d) && (f != e)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint6;
            }
            Retrypoint7:
            int g = int.Parse(Console.ReadLine());
            if ((g > 10) && (g < 100) && (g != a) && (g != b) && (g != c) && (g != d) && (g != e) && (g != f)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint7;
            }
            Retrypoint8:
            int h = int.Parse(Console.ReadLine());
            if ((h > 10) && (h < 100) && (h != a) && (h != b) && (h != c) && (h != d) && (h != e) && (h != f) && (h != g)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint8;
            }
            Retrypoint9:
            int i = int.Parse(Console.ReadLine());
            if ((i > 10) && (i < 100) && (i != a) && (i != b) && (i != c) && (i != d) && (i != e) && (i != f) && (i != g) && (i != h)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint9;
            }
            Retrypoint10:
            int j = int.Parse(Console.ReadLine());
            if ((j > 10) && (j < 100) && (j != a) && (j != b) && (j != c) && (j != d) && (j != e) && (j != f) && (j != g) && (j != h) && (j != i)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint10;
            }
            Console.WriteLine("The numbers you entered were " + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ", " + h + ", " + i + " & " + j);
            Console.WriteLine("Please press enter to continue");
            Console.ReadKey();

Upvotes: 1

Views: 4239

Answers (6)

shadi
shadi

Reputation: 358

I would prefer not to store the invalid input in first place:

Console.Write("\nEnter your number:\t");
int input = Convert.ToInt32(Console.ReadLine());
if (input < 10 || input > 100 || arr.Contains(input))
    Console.WriteLine("You did not enter a valid number.");
else
{
    arr[a] = input;
    //When they do meet the correct values
    Console.WriteLine("Thanks for entering the number " + arr[a]);
}

Upvotes: 0

pblyt
pblyt

Reputation: 518

You may try the following with more validation (see comment code):

static void Main(string[] args)
    {
        int[] arr = new int[10]; // The size of the array is 10
        int input;
        int savedNumCount = 0;
        const int MIN = 10;  // Use constant to set the range instead
        const int MAX = 100; // of typing them in code

        Console.WriteLine("Please enter 10 numbers between 10 and 100. They cannot be identical.");
        do
        {
            if (int.TryParse(Console.ReadLine(), out input) == false)
            { // Check if number is entered
                Console.WriteLine("Please enter a number.");
                continue;
            }
            if (input < MIN || input > MAX)
            { // Check range
                Console.WriteLine("The number you entered does not fall between 10 and 100.\r\n Please try again.");
                continue;
            }                
            if (savedNumCount == 0)
            { // Compare with existing numbers
                arr[savedNumCount] = input; // No checking for 1st input
                savedNumCount++;
            }
            else
            {
                if (!arr.Contains(input))
                {
                    arr[savedNumCount] = input;
                    savedNumCount++;
                }
                else
                {
                    Console.WriteLine("The number you entered is identical to one of the other numbers. Please try again");
                }
            }
        }
        while (savedNumCount < arr.Length);

        string result = "The numbers you entered were ";
        foreach (int num in arr)
            result += num.ToString() + "  ";
        Console.WriteLine(result);
        Console.WriteLine("Please press enter to continue");
        Console.ReadKey();
    }

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

Something like this should work for you, I am using TryParse to filter out non numeric characters and a do while loop, I also am using the Contains Linq Extension method to check for duplicates . See if this will work for you.

static void Main(string[] args)
{
    int[] arr = new int[10];
    int count = 0;
    int a;
    do
    {
        if (int.TryParse(Console.ReadLine(), out a)) //Verify that input is numeric
        {
            if ((a > 10) && (a < 100))  //Check Constraints
            {
                if (!arr.Contains(a))   //Check for duplicates
                {
                    arr[count] = a;    //Only if we get here then input into array
                    count++;           //Increment to next Index
                }
            }
        }
    } while (count < 10);             //Rinse and repeat to you get 10 valid entries

    Console.ReadLine();
}

Upvotes: 0

Corey
Corey

Reputation: 16564

A few issues, at least two of which have been mentioned already:

  1. Your code does not check that the entered text is actually a number. If the user enters something that is not a number, Convert.ToInt32 will throw an exception.

  2. With --arr[a] You are decrementing the value at position a in the array, not the value of a.

  3. Do not goto without a very good reason. Even in test code.

Here's some code that should cover most of what you are trying to do:

int[] arr = new int[10];

for (int a = 0; a < 10; )
{
    // Get number from user
    Console.Write("Enter number: ");
    string entered = Console.ReadLine();
    int val;

    // check for valid integer entered
    if (!Int32.TryParse(entered, out val))
        Console.WriteLine("Invalid number '{0}'", entered);
    // check number in allowed range
    else if (val < 10 || val > 100)
        Console.WriteLine("Value '{0}' out of allowed range (10-100)", val);
    // check number not already supplied
    else if (a > 0 && arr.Take(a).Contains(val))
        Console.WriteLine("Value '{0}' already entered");
    // add to array
    else
    {
        arr[a++] = val;
        Console.WriteLine("Added value '{0}'.  {1} remaining.", val, 10 - a);
    }
}

Upvotes: 0

Adam Schmalhofer
Adam Schmalhofer

Reputation: 106

The problem is here:

 if (arr[a] < 10 || arr[a] > 100)  // I tried using brackets and && nothing worked
 {
 // If they do not meet the correct information
 Console.WriteLine
 ("You did not enter a valid number.");
 --arr[a];
 }

With --arr[a] you are reducing the value that the user entered nor throwing it away. What you wanted to write is --a instead.

To check that the user entered the number double you could check by adding to the if(…)

 || arr.Take(a).Contains(arr[a])

Upvotes: 2

Andrew Crawford
Andrew Crawford

Reputation: 196

Your problem is here:

--arr[a];

You should be decrementing a, not the value in the array. Try this instead:

a--;

Upvotes: 0

Related Questions