java - What is wrong with my method isReverse -


write recursive method called isreverse("word1", "word2") accepts 2 strings parameters , returns true if 2 strings contain same sequence of characters each other in opposite order, ignoring case, , returning false otherwise. example, call of:

isreverse("desserts", "stressed")  

would return true. [so eat desserts when stressed?] null, empty , 1 letter strings return true (if both parameters same value). homework , having trouble making code work appropriately. returns true no matter do.

public static boolean isreverse(string word1, string word2)  {     if(word1 == null || word2 == null)     {         if(word1!= null && word2 != null)         {             return false;         }         return false;     }     else if(word1.length() == word2.length())     {         string firstword = word1.substring(0, word1.length());         string secondword = word2.substring(word2.length()-1);         if (firstword.equalsignorecase(secondword))         {              return isreverse(word1.substring(0, word1.length()), word2.substring(word2.length() - 1));         }     }     return true; } 

is exercise? recursion doesn't seems best option here. anyway, you're trimming 1 word, why? must trim both words if expect compare each char in each recursive call. , you're not passing trimmed words parameter recursive function!

the basic thing you're missing base case. when recursion must return? in case, you're reducing each string size @ each step of recursion, must have base case check if size one.

hope code clear mind:

public static boolean isreverse(string word1, string word2) {     if (word1 == null || word2 == null) {         return false;     }     if (word1.length() == 1 && word2.length() == 1) {         //used equals fast compare         return word1.equals(word2);     } else if (word1.length() == word2.length()) {         if (word1.charat(0) == word2.charat(word2.length() - 1)) {             string firstword = word1.substring(1, word1.length());             string secondword = word2.substring(0, word2.length() - 1);             system.out.printf("trimmed %s, %s %s, %s\n", word1, word2, firstword, secondword);             return isreverse(firstword, secondword);         } else {             //characters didn't matched             return false;         }     } else {         //lenght doesn't match         return false;     } } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -