2012-01-24 237 views
0

我正在使用的语言中没有任何gotojump函数。例如,Matlab。 你能帮我解决如何避免使用它吗?有没有简单的技巧来解决我的问题?goto和jump命令的替代方法

+4

如果没有'在MATLAB goto',那么你应该没有问题,避免它;)在M文件跳转]的 – Chris

+1

可能重复(HTTP://计算器.com/questions/1082605/jump-in-m-file) – gnovice

回答

1

那么,首先你不妨问一下没有这个标签,你可能会得到更好的答案。这是因为几乎所有现代语言都存在这种问题。

代替gotojump你应该使用条件语句像ifif-else或循环一样whilefor,这取决于你想要达到的目标。

结账GOTO still considered harmful?,Why is goto poor practise?

3

您应该考虑使用breakcontinue

相反的:

for ... 
    ... 
    if ... 
     goto nextstuff: 
    end 
end 
nextstuff: 

你可以这样做:

for ... 
    ... 
    if ... 
     break 
    end 
end 

而作为@andrey说,你通常可以通过if-else

更换 goto

而不是做的:

if cond 
    goto label 
end 
... 
foobar() 
... 
label: 
foobar2() 

,你可以这样做:

if ~cond 
    ... 
    foobar() 
    ... 
end 
foobar2() 

当您使用goto语句回去,你可以通过同时替换:

而不是做的:

redothat: 
foobar() 
... 
if cond 
    goto redothat; 
end 

你可以做:

while cond 
    foobar() 
    ... 
end 
+0

非常感谢您的回复,我很抱歉发现错误的标签。我的问题是我想实现一个状态图(网格编码),我必须回到我的code.I不知道是否有什么明显的地方我不能看到(很可能),但我找不到解决方案。 –

+0

你应该更详细地描述你的问题,如果你想要一个不太普遍的答案... – Oli

+0

我有一个100个随机(二进制)数字的序列。 –

1

As @Andrey提及您可以使用ifif-else声明。在很多情况下,像whilefor这样的循环是if-elsegoto的一对一替代品。

您还应该考虑使用breakcontinue声明,如@Oli上面所述。

在一些罕见的情况下,您可以使用异常(我不知道Matlab是否支持它)以便“返回”。这有点争议,但在你的情况下它可能适合。

while(true){ 
try { 
    foobar(); 
    ... 
    break; 
} 
catch(YourApplicationException e){ 
    //do nothing, continiue looping 
} 
} 

而且里面foobar的()在一些地方,你

if cond 
    throw YourApplicationException(); 
end 

redothat: 
foobar() 
... 
在一些地方,你

if cond 
    goto redothat; 
end 

你可以做

而且里面foobar的()

或者你可以这样做:

你可以这样做:

boolean isOk = false; 
while(! isOk){ 
try { 
    foobar(); 
    ... 
    isOk=true; 
} 
catch(YourApplicationException e){ 
    //do nothing, continiue looping 
} 
}