2

我有无限递归的问题。Main 方法将运行,然后如果我选择 1,它将转到 submenu()。但是,当我在 submenu() 中选择了错误的选项时,程序必须循环回 main 方法。

但是,这种情况会导致堆栈溢出。

你对这个问题有什么想法吗?它如何在不调用 main() 的情况下循环回 main 方法?

非常感谢你们。

   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();
      }
   }
4

1 回答 1

4

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. You can still say return if you want to return from a place that is not the end of the method.

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. Just remove the call to main().

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

于 2012-04-19T16:11:18.930 回答