0

I'm pretty new to C# and want the users to be able to write in 5 numbers between 1 to 25. The issue I'm having is that I don't want the user to type a number over 25 or a number below 1.

Also this is a task for my studies and my teacher want us to use arrays so I'm not allowed to use List.

        int[] usernum = new int[4];

        for (int i = 0; i < usernum.Length; i++)
        {
            usernum[i] = Convert.ToInt32(Console.ReadLine());
        }
4
  • Welcome to StackOverflow, if you want your user not be able to enter a number lower then 1 or higher than 25 you need to check for that. Commented Oct 9, 2020 at 11:05
  • 1
    If you want 5 values, your array should have length 5, not 4. Commented Oct 9, 2020 at 11:05
  • I would advise you to first look into If statements learn.microsoft.com/en-us/dotnet/csharp/language-reference/… and trying to understand how to solve it yourself instead of asking for help. Commented Oct 9, 2020 at 11:05
  • Also, do not use Convert.ToInt32, use int.TryParse. Commented Oct 9, 2020 at 11:09

3 Answers 3

4

Ok, to start off, some annotations to your code:

int[] usernum = new int[4]; // should be: new int[5];

for (int i = 0; i < usernum.Length; i++)
{
    usernum[i] = Convert.ToInt32(Console.ReadLine()); // use int.TryParse instead
}

Now, I don't want to just give you the code, since this should obviously be a learning experience.

What you need to do, though is integrate a "validation" cycle. That means:

  1. Read in string from user
  2. Try to parse string to number
    If that fails: back to 1.
  3. Check if number < 1 or > 25
    If so: back to 1.
  4. If you are here, you passed both checks and can set usernum[i] = number
  5. Next "i"

Obviously, there are some slight variations in how you twist and turn your checks and arrange loops which are equally valid.

For example: You can decide if you want to check if number is inside bounds or if you want to check if the number is outside bounds and jump or not jump accordingly ...


Why int.TryParse instead of Convert.ToInt32?

There are some rule of thumbs that can spare you from severe headaches:

  • "Never trust user input"
  • "Do not use exceptions for control flow"

Using Convert here, breaks both.

For one, Convert.ToInt32 throws if the string does not represent an integer value (chars other than +-0..9, value > int.Max or < int.Min). So in using it, you trust the user to type in a valid integer. Not a good idea.

Then, it throwing means: the case, that a user (maybe just made a typo) did not provide valid input is controlling your flow to error handling. But this case is not at all "exceptional". In fact, you should expect it. int.TryParse makes this possible, in that it returns you a flag (boolean) that informs you about success or failure of the conversion attempt (instead of throwing).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate. I will try this out and see if I can figure it out.
0

Though I would recommend you to learn if else loop first https://www.w3schools.com/cs/cs_conditions.asp

here is the code if needed

int[] usernum = new int[4];
        for (int i = 0; i < usernum.Length; i++)
        {
            var result = Console.ReadLine();
            int currentResult;
            if (!int.TryParse(result, out currentResult))
            {
                Console.WriteLine("Invalid input - must be a valid integer value");
                i--;
                continue;
            }
            if(currentResult < 1 || currentResult > 25)
            {
                Console.WriteLine("Invalid input - must be between 1 & 25");
                i--;
                continue;
            }
            usernum[i] = currentResult;
        }

1 Comment

Thanks legend. This helped, I know how if/else works.I don't quite understand all of the code you gave me so I will have some studying to do.
0

for-loop might not be the ideal solution for this use-case where you need to conditionally increment the index.

This should do the trick:

int[] userNumbers = new int[5];

int i = 0;

while (i < userNumbers.Length)
{
    string rawInput = Console.ReadLine();
    
    bool isNumberValid = int.TryParse(rawInput, out int inputNumber); // as suggested by @Fildor
    
    if(isNumberValid && inputNumber >= 1 && inputNumber <= 25) // increment counter only if 1 <= input <= 25
    {
        userNumbers[i] = inputNumber;
        i++;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.