简体   繁体   English

如何解决Java中的无限递归(堆栈溢出)?

[英]How to solve infinite recursion in java (stack overflow)?

I have problem with infinite recursion. 我有无限递归的问题。 Main method will run, then if I chose 1, it will go to submenu(). Main方法将运行,然后如果我选择1,它将转到submenu()。 But, when I choose a wrong option in submenu(), the program must be loop back to main method. 但是,当我在submenu()中选择了错误的选项时,该程序必须循环回到main方法。

However, this situation can result stack overflow. 但是,这种情况可能导致堆栈溢出。

Do you have any ideas guys related to this problem? 您有与此想法相关的想法吗? How could the it loop back to main method without calling the main()? 它如何不调用main()循环回到main方法?

Thanks a lot guys. 非常感谢。

   public void main() {
      // variables omitted
      while (menu) {

         switch (option) {
         case 1:
            subMenu();
            break;
         }
      }

   }

   public void subMenu() {
      switch (a) {
      case 1:
      case 2:
      default:
         System.out.println("Invalid Option");
         main();
      }
   }

You don't need to call main() to return to the main method, to return from a method, you say return <vairable> , or if the method is a void return type, no return is needed at the end of the method. 您不需要调用main()返回main方法,也不需要从方法返回,只需说return <vairable> ,或者如果该方法是空返回类型,则在方法末尾不需要返回。 You can still say return if you want to return from a place that is not the end of the method. 如果您想从方法结束的地方return ,您仍然可以说return

So in your case above, the switch is the last element in the subMenu method, so after the switch, the method is finished, so returns. 因此,在上述情况下, switchsubMenu方法中的最后一个元素,因此在切换之后,该方法完成,因此返回。 Just remove the call to main() . 只需删除对main()的调用即可。

Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html 看看http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM