Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrying until the user input is correct

Tags:

c#

I'm learning C# via Rob Miles Yellow Book and have hit a problem with understanding variable scope.

The class I have developed (at the bottom) asks for a number and then displays it back to user. I would like to enhance it so that if the user enters ten instead of 10 it outputs a message and the user has another attempt.

Here is one of several attempts so far at the change...

...

    static int readInt(string prompt, int low, int high)
    {
        int result;

        do
        {
            try
            {
                string intString = readString(prompt);
                result = int.Parse(intString);
                Console.WriteLine("Thank you");
            }
            catch
            {
                Console.WriteLine("Invalid age value");
            }

        } while ((result < low) || (result > high));

        return result;
    }
...

Unfortunately this has the effect (I think) of pushing result out of scope because with this change I see the following compliation error:

CS0165 Use of unassigned local variable 'result'

What is the C# way to achieve this?

The complete class:

using System;

class Exception1
{
    static string readString(string prompt)
    {
        string result;

        do
        {
            Console.Write(prompt);
            result = Console.ReadLine();
        } while (result == "");

        return result;
    }

    static int readInt(string prompt, int low, int high)
    {
        int result;

        do
        {            
            string intString = readString(prompt);
            result = int.Parse(intString);            
        } while ((result < low) || (result > high));

        return result;
    }


    public static void Main()
    {
        const int SCORE_SIZE = 1;

        int[] scores = new int[SCORE_SIZE];

        for (int i = 0; i < SCORE_SIZE; i++)
        {
            scores[i] = readInt("Score : ", 0, 1000);

        }

        for (int i = 0; i < SCORE_SIZE; i++)
        {
            Console.WriteLine("Score " + i + " is " + scores[i]);
        }

        Console.Read();
    }
}    
like image 935
Ian Carpenter Avatar asked May 01 '26 04:05

Ian Carpenter


2 Answers

The compiler doesn't know that the while loop actually runs (it can throw and exception before assigning result) and sets a value on result. Therefore it complaints about this.

You can circumvent this by assigning a default value to result:

int result = -1;

Or by setting a value in the catch block:

catch
{
    result = -1;
    Console.WriteLine("Invalid age value");
}

I always use -1 in these cases as indicator of 'something wrong with this value'.

like image 96
Patrick Hofman Avatar answered May 03 '26 14:05

Patrick Hofman


Just wanted to add possible solution if you really don't want to set result to any value initially:

static int readInt(string prompt, int low, int high)
{            
    bool validInput;
    int result;

    do
    {
        if ((validInput = int.TryParse(readString(prompt), out result)))
            Console.WriteLine("Thank you");
        else
            Console.WriteLine("Invalid age value");

    } while (!validInput || (result < low) || (result > high));
}

If TryParse fails, result will be set to integer default value (0) and validInput variable will be set to false so loop will go through once again.

like image 32
msmolcic Avatar answered May 03 '26 13:05

msmolcic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!