首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >the infame Goto,Java,automatic code

the infame Goto,Java,automatic code
EN

Stack Overflow用户
提问于 2012-05-07 18:49:23
回答 3查看 172关注 0票数 2

假设你有这样一段Java代码:

代码语言:javascript
复制
public class MyClass {
    public static Object doSmthg(Object A,Object B){
        if(smthg){ //if is given has an example, it can be any thing else
            doSmthg;
            GOTO label;
        }
        doSmthg;

        label;
        dosmthg1(modifying A and B);
        return an Object;
    }
}

我正在自动生成代码。当生成器到达生成goto的时刻(并且它不知道它在if块中)时,它不知道后面会发生什么。

我尝试使用标签,中断,继续,但这不起作用。

我尝试使用一个内部类(执行dosmthg1),但A和B必须声明为final。问题是A和B必须修改。

如果没有其他解决方案,我将不得不在我的生成器中传播更多的知识。但我更喜欢一种更简单的解决方案。

有什么想法吗?

提前谢谢。

EN

回答 3

Stack Overflow用户

发布于 2012-05-07 18:58:22

代码语言:javascript
复制
public static Object doSmthg(Object A,Object B){
    try {
    if(smthg){ //if is given has an example, it can be any thing else
        doSmthg;
        throw new GotoException(1);
    }
    doSmthg;

    } catch (GotoException e) {
         e.decrementLevel();
        if (e.getLevel() > 0)
            throw e;
    }
    dosmthg1(modifying A and B);
    return an Object;
}

人们可以使用异常来做gotos,但是为了定位正确的“标签”,人们要么必须检查异常消息,要么必须考虑嵌套级别。

我不知道我是否觉得这不是更丑陋。

票数 1
EN

Stack Overflow用户

发布于 2012-05-07 18:58:47

您可以在标签前面的块周围添加一个虚拟循环,并使用标签为break的等价物goto:

代码语言:javascript
复制
public static Object doSmthg(Object A,Object B){
    label:
    do { // Labeled dummy loop
        if(smthg){ //if is given has an example, it can be any thing else
            doSmthg;
            break label; // This brings you to the point after the labeled loop
        }
        doSmthg;
    } while (false); // This is not really a loop: it goes through only once
    dosmthg1(modifying A and B);
    return an Object;
}
票数 1
EN

Stack Overflow用户

发布于 2012-05-07 19:00:23

如果你想跳过某个东西,就像这样:

代码语言:javascript
复制
A
if cond goto c;
B
c: C

你可以这样做

代码语言:javascript
复制
while (true) {
    A
    if cond break;
    B
}
C
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10480722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档