Page 1 of 1

Do while loop in C# [SOLVED]

Posted: Fri Jan 20, 2012 12:28 am
by mattykins
I ask you guys way too many noob questions haha i'm sorry.

So i'm writing a do while loop as a test and my code thus far looks like this:

Code: Select all

           do
            {
                string userinput;
                userinput = Convert.ToString(Console.ReadLine());
            }
            while (userinput != "escape");
And I get the error 'userinput' does not exist in the current context.

Is it because i declared userinput inside of the loop?

Thanks in advanced :)

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:34 am
by Zak Zillion
I've been learning java and not C# lol but I think its because userinput is considered a local variable, for you to be able to use it in the while statement you'd have to make it a class variable or something :P I hope that helps!

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:46 am
by mattykins
Thanks! But how would i go about doing that?

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:50 am
by Zak Zillion

Code: Select all

do
            {
                string userinput;
                userinput = Convert.ToString(Console.ReadLine());
                return userinput;
            }
            while (userinput != "escape");
I think this is how you do it! Hopefully it's something like java. :P All this does is return the local variable to the class.

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:52 am
by mattykins
I'll try that right now :) Thanks. I'm still pretty noob here heh.

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:54 am
by Zak Zillion
Good luck! I am too. :P

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:54 am
by mattykins
Sorry for double post! But its giving me the same error even with return userinput;

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:56 am
by Zak Zillion
Well this is the point were I hand it off to the more experienced devs. ;)

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 4:59 am
by Jackolantern
You can't return a variable from a FOR loop. Only from methods. Set it up like this:

Code: Select all

   string userinput = "";
   do
   {                
       userinput = Convert.ToString(Console.ReadLine());
   }
   while (userinput != "escape");
That way the userinput variable will be available both inside and outside of the DO-WHILE loop.

Re: Do while loop in C#

Posted: Fri Jan 20, 2012 5:27 am
by mattykins
Awesome man :) Thanks.