ivan angelo
ivan angelo

Reputation: 157

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

Upvotes: 2

Views: 5708

Answers (1)

Noel M
Noel M

Reputation: 16116

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

Upvotes: 4

Related Questions