Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-19-2012, 10:38 PM   PM User | #1
trantommyd
New Coder

 
Join Date: Mar 2012
Posts: 30
Thanks: 1
Thanked 0 Times in 0 Posts
trantommyd is an unknown quantity at this point
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?

Code:
	public static void SearchStack(Stack s1, Stack s2, int key)
	{
			Scanner keyboard = new Scanner(System.in);
			boolean found = false;
			while(!s1.empty())
			{
				int compare = (Integer)s1.pop();
				if(compare == key)
				{
					System.out.println(key + " was found.");
					found = true;
				}
				s2.push(compare);
			}
			if(!found)
			{
				System.out.println(key + " was not found.");
			}
			
			System.out.println("Would you like to search for another value? Enter N if you do not.");
			if(keyboard.next().equalsIgnoreCase("N"))
			{
				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..
trantommyd is offline   Reply With Quote
Old 07-20-2012, 03:25 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,661
Thanks: 4
Thanked 2,452 Times in 2,421 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:06 AM.


Advertisement
Log in to turn off these ads.