【问题标题】:Core Java Programming核心 Java 编程
【发布时间】:2017-05-15 10:33:40
【问题描述】:

我正在使用 Eclipse SWT 编写代码,如果满足某个条件,则执行会进一步推进,如果不满足,它应该恢复到之前的执行 执行点。任何人都可以帮忙吗? 看起来是这样的

void main(){
    methodA();
    methodB();
}

methodA(){

    if(x==y)
    {
        //continue the execution further
    }
    else
    {
        //once again go to back the calling method (i.e) methodA() and 
        //not methodB() as compiler usually does
    }
}

简而言之:我需要与 C++ 中的 goto 关键字类似的东西

提前致谢, 萨蒂什

【问题讨论】:

  • 你可以使用标签,但我觉得你做错了......
  • 开始阅读java文档并同时练习
  • 使用循环。例如,在您的教科书或在线教程中了解 while 循环。

标签: java eclipse swt core


【解决方案1】:

如果methodA() 失败,您是要跳过methodB() 调用还是要再次调用methodA()

private boolean methodA() {
    boolean _success = false;



    if(x==y)
    {
       _success = true;
       //continue the execution further
    } else {
        //.....
    }

   return _success;

}

然后在main()中

if (methodA()) {
    methodB();
}

或者如果你想在 main 中再次调用methodA()

while(!methodA()) {
//...?

} 

methodB();

一些参考资料:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

https://docs.oracle.com/javase/tutorial/java/TOC.html

【讨论】:

  • 如果,如果方法 A 的一部分失败,否则执行,我需要再次调用方法 A,并且在方法 A 和方法 B 的返回类型为 void
  • 更改方法的返回类型或将while循环移到methodA()中
【解决方案2】:

不要使用goto,而是使用循环。这样你就可以继续运行methodA中的代码,直到满足条件,然后继续methodB

   void main(){
       methodA();
       methodB();
   }

   methodA(){
       while(x!=y)
       {
           // the body of methodA
       }

       //continue the execution further
   }

【讨论】:

  • 非常感谢您。但是,条件是仅在单击一次时发生的事件。它就像一个布尔值
【解决方案3】:

这是一个代码,你可以使用。

public class Test{

public static void main(String[] args){

    methodA();
    methodB();
}

static void methodA(){
    int x = 2;
    int y = 4;

    repeat: while(x!=y){

        System.out.println(x + " is not equal to " + y);
        x++;

        continue repeat; // to show you how to have goto statement in Java; but it is not necessary in this case
    }

    if(x==y){
        System.out.println(x + " is equal to " + y);
    }

}

static void methodB(){

    System.out.println("I'm methodB()");
}
}

【讨论】:

  • 谢谢!!!但问题是 input 是一个事件,它是 Boolean 。所以 X!=Y 在这种情况下无效
【解决方案4】:
        void main(){
    methodA();
    methodB();
}

methodA(){
boolean status = true;
    if(x==y)
    {
        //continue the execution further
    }
    else
    {
    if(found == true)
    {
    while(found)
    {
        methodA();
    }
    }
    else {
    found = false;
    }
    }
}

这可能是递归解决方案,如果条件满足,方法会调用自身。 否则它终止。 希望对你有帮助!!

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    相关资源
    最近更新 更多