Hi!
I'm quite new to Java and I've got this question that requires me to solve a basic algorithm.
"Implement a method public static boolean compareLast4(String s1, String s2) that returns true if the final four-character substrings of s1 and s2 are equal. If the length of either string is less than 4, the method should return false.
You may use the methods.substring(n,m) that yields the substring of s beginning at index and ending at index m-1."
Here's my code:
public class compareLast4 { public static void main(String[] args){ String s1 = "Elephant"; String s2 = "Tiger"; System.out.println(compareLast4(s1,s2)); } public static boolean compareLast4(String s1, String s2){ int p1 = s1.length() - 4; int p2 = s2.length() - 4; int t1 = 0; int t2 = 0; for (int i = p1; i < s1.length(); i++) { t1++; } t1+=p1; for (int j = p2; j < s2.length(); j++) { t2++; } t2+=p2; if(s1.substring(p1, t1) == s2.substring(p2, t2)){ return true; } else{ return false; } } }
No matter what words I put in there, it's always false. The pointer is there to show the starting index of the string and it will count to the end. For example, "Elephant" starts at index 5, which is "h" until it reaches "t" and "tiger" starts at index 1 which is "i" until it reaches "r".
Am I missing something?
--- Update ---
I've actually solved the problem, funnily enough.
The following line has been added:
if(s1.substring(p1, t1).length() == s2.substring(p2, t2).length()){ return true; }