goto命令不起作用
问题描述:
当我在没有goto命令的情况下执行代码时,它可以工作,但是当我添加:Start
时,它会得到一个8错误。goto命令不起作用
下面是相关代码:
:Start
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
break;
case "no":
Console.WriteLine("You choose no");
break;
default:
Console.WriteLine("{0},is not a word",what);
goto Start;
}
答
正确的语法是Start:
。但是,不是goto
,你应该在一个循环中进行设置:
bool invalid = true;
while (invalid)
{
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
invalid = false;
break;
case "no":
Console.WriteLine("You choose no");
invalid = false;
break;
default:
Console.WriteLine("{0},is not a word",what);
}
}
+2
'while(invalid)'看起来更符合逻辑 – 2014-10-31 15:18:13
+0
@AlexK。是的,我同意。 – 2014-10-31 15:23:51
答
试试 “开始:” 而不是 “:启动” 这样的:
Start:
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
break;
case "no":
Console.WriteLine("You choose no");
break;
default:
Console.WriteLine("{0},is not a word", what);
goto Start;
}
http://msdn.microsoft.com/en-us/library/aa664740(v=vs.71).aspx
答
一个标签的正确的语法是Start:
,不:Start
您可以重构代码省略goto语句代替(better ):
bool continue = true;
while (continue) {
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
continue = false;
break;
case "no":
Console.WriteLine("You choose no");
continue = false;
break;
default:
Console.WriteLine("{0}, is not a word",what);
break;
}
}
转到哪种语言? – 2014-10-31 15:12:47
正确的标签语法:'开始:' – 2014-10-31 15:14:44
请不要太习惯goto语句:https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF:D – SlySherZ 2014-10-31 15:15:58