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 11-29-2010, 09:53 PM   PM User | #1
NutmegState
New to the CF scene

 
Join Date: Oct 2010
Location: Boston
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
NutmegState is an unknown quantity at this point
Quick question on recursive method with strings

Hi, I am taking an Intro to Java class right now, and one of our assignments is to write a code that uses a recursive method to compare one string to the reverse of another string (ignoring capitalization). The following code will compile, but will always return the false result, even when it should clearly return true. Can anyone help me find my mistake? Thank you very much!

Code:
import java.util.*;

public class CompareString {

	public static void main(String[] args) {
	
	    Scanner console = new Scanner(System.in);
	
	    System.out.print("Please enter a string: ");
	    String firstString = console.nextLine();
	
	    System.out.print("Please enter another string: ");
	    String secondString = console.nextLine();
	
        boolean comparison = isReverse(firstString, secondString);
    
        if (comparison == true) {
            System.out.println("The reverse of one string is the same as the  
            other string, ignoring capitalization.");
        } else {
            System.out.println("The reverse of one string is not the same as the 
            other string.");
	        }
	}
	
	public static boolean isReverse(String firstString, String secondString) {
	
	    String temp = null;
	    
	    if (firstString.length() == 1) {
		    temp = temp + firstString.substring(0, 1);
	        }
	            
	    else {
	                
		    String lastChar = firstString.substring(firstString.length() - 1, 
                    firstString.length());
		
		    String remainingString = firstString.substring(0, 
                    firstString.length() - 1);

		    temp = lastChar + isReverse(remainingString, secondString);
		    }
	    
	    if (temp.equalsIgnoreCase(secondString)) {
	        return true;
	        
	    } else {
	        return false;
	        }
	}
}
NutmegState 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 01:02 AM.


Advertisement
Log in to turn off these ads.