Jordan Olivas
Jordan Olivas

Reputation: 11

Receiving user input from do while statement

I'm at a total loss here... The logic seems to be setup correctly but the "response" in the while statement says it doesn't exist in the current context. I searched on here and quite seem to find the same issue in this context. Is the issue the conver to method?

    do
        {
            Console.WriteLine("enter a number between 1 and 5");
            int x = Convert.ToInt32(Console.ReadLine());

            Random r = new Random();
            int rr = r.Next(1, 5);
            Console.WriteLine("Do you want to continue?  Please select yes or no.");
            string response = Convert.ToString(Console.ReadLine());
        } while (response == "yes");

Upvotes: 1

Views: 528

Answers (3)

David Cardinale
David Cardinale

Reputation: 153

Might help to encapsulate this a bit. How about:

static void Main(string[] args)
    {
        Random rand = new Random();
        do
        {
            Write("enter a number between 1 and 5");
            string response = Console.ReadLine();
            int x = 5;
            if (Validate(response, "1-5")) int.TryParse(response, out x);                
            Write(rand.Next(0,x));
            Write("Do you want to continue?  Please select yes or no.");                
        } while (Validate(Console.ReadLine().ToLower(), "yes"));
    }
    static void Write(string s) => Console.WriteLine(s);
    static bool Validate(string s, string Pattern) => Regex.Match(s, Pattern).Success; 

Upvotes: 0

Thomas Fitzgerald
Thomas Fitzgerald

Reputation: 103

Your response variable is not in the context of the loop. Simply move the variable declaration outside the loop as below:

        string response = String.Empty;

        do
        {
            Console.WriteLine("enter a number between 1 and 5");
            int x = Convert.ToInt32(Console.ReadLine());

            Random r = new Random();
            int rr = r.Next(1, 5);
            Console.WriteLine("Do you want to continue?  Please select yes or no.");
            response = Convert.ToString(Console.ReadLine());
        } while (response == "yes");

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Variables declared in one scope (generally a set of braces { ... }) are not accessible outside of that scope. You've declared response inside the loop. You need to declare response outside of the loop.

You also want to trim whitespace from the string before comparing it, using String.Trim(). Otherwise there will be a newline character (\n) at the end, causing your comparison to fail.

string response;

do {
    //...

    response = Console.ReadLine().Trim();
} while (response == "yes");

Upvotes: 6

Related Questions