Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2012
    Thanked 0 Times in 0 Posts

    Recursive Method Infinite Loop

    *** EDIT ***
    I found my problem. The method was being called inside of a while loop in the main method that had a boolean value that was never being changed. Mods, please delete this thread.

    I have written a search method to search thru a stack. The idea is for it to recursively call itself if the user enters any key but 'n'. If the user enters 'n', I want the method to end and to return to main.
    Right now, my problem is that this method seems to be infinitely calling itself instead of exiting once 'n' is entered. Can you help me find my error?

    	public static void SearchStack(Stack s1, Stack s2, int key)
    			Scanner keyboard = new Scanner(System.in);
    			boolean found = false;
    				int compare = (Integer)s1.pop();
    				if(compare == key)
    					System.out.println(key + " was found.");
    					found = true;
    				System.out.println(key + " was not found.");
    			System.out.println("Would you like to search for another value? Enter N if you do not.");
    				System.out.println("Enter a value to search the stack for: ");
    				int find = keyboard. nextInt();
    				SearchStack(s2, s1, find);
    Last edited by trantommyd; 07-19-2012 at 10:42 PM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Saskatoon, Saskatchewan
    Thanked 2,659 Times in 2,628 Posts
    I'm glad you found the cause.
    I'll leave this thread available though. It's very easy to get caught in a deadly spiral when it comes to recursive calls and looping outside of it, so hopefully if someone searches for infinite recursion on otherwise correct code, they may see this thread and realize that there may be an external infinite loop.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts