2

I have problem with infinite recursion. Main method will run, then if I chose 1, it will go to submenu(). But, when I choose a wrong option in submenu(), the program must be loop back to main method.

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()?

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();
      }
   }
4
  • 5
    Solution: don't use recursion here as it would be much better to simply use a while loop. Commented Apr 19, 2012 at 15:35
  • 1
    you already have a while menu in main.. so why not just return? instead of main() do return? Commented Apr 19, 2012 at 15:38
  • Consider having your subMenu method return a value, it could be as simple as a boolean, to let the calling code know whether it was successful or not, and if not, then continue with the while loop. Commented Apr 19, 2012 at 15:44
  • 2
    Also: what does this have to do with javascript? That tag just makes no sense. Commented Apr 19, 2012 at 15:45

1 Answer 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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Noel for the answer. Thats very helpful.
Thanks guys for the help. Im newbie in java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.