PDA

View Full Version : C# Moving around the script


patrickcabenjamin
12 Apr 2009, 1:28pm
Hi

I am a C# noob, most of the things i know about it i have asked on Icrontic. I want to find a way to go to another part in the script.




for example

System.Console.Out.WriteLine("do you want to exit");
string1 = System.Console.In.ReadLine();
if (string1.ToLower().Contains"yes"))
{
//here it would go to the end
}
else
//here it would continue the script



or if it goes back

System.Console.Out.WriteLine("hello");
System.Console.Out.WriteLine("do you want me to repeat that");
string1 = System.Console.In.ReadLine();
if (string1.ToLower().Contains"yes"))
{
//here it would go back
}
else
//here it would continue the script




is this possible? and if so how?

pragtastic
12 Apr 2009, 1:49pm
You could wrap it in a while loop that is conditionalized to a predefined variable, and then updated based on the user's input, like so:


bool continue = true;
while(continue)
{
System.Console.Out.WriteLine("hello");
System.Console.Out.WriteLine("do you want me to repeat that");
string1 = System.Console.In.ReadLine();
if (string1.ToLower().Contains("yes")) // fixed this to match the "yes"
{
continue; // this breaks out of the current iteration of the while loop and starts over at the beginning
}
else
//here it would continue the script
}


This is just one of many ways to achieve this sort of looping.

patrickcabenjamin
12 Apr 2009, 2:05pm
i've tried this and it dosn't work
the error underline appears under everywhere where i have written continue

pragtastic
12 Apr 2009, 2:14pm
My apologies, continue is a reserved keyword in C#, I was just going for a variable of type bool, so replace "bool continue = true;" with "bool keepGoing = true;"

Then replace "while(continue)" with "while(keepGoing)"

Also, I just realized that I forgot to change the value of sentinel (keepGoing in this case) to false at some point so it doesn't keep looping. So inside the else{} make the first line "keepGoing = false;"

patrickcabenjamin
12 Apr 2009, 2:25pm
oh, okay
thankyou
:-)

but now when i have
_______________________________
if (string1.ToLower().Contains("yes"))
{
keepgoing;
}
_______________________________

the word keepgoing becomese underlined

pragtastic
12 Apr 2009, 3:03pm
That is where the real use of "continue;" should be, its a keyword that breaks out of the current iteration of the while loop and starts back over from the top.

patrickcabenjamin
12 Apr 2009, 3:06pm
oh, i see

thanks very much

:-)