RoboticPlayer RoboticPlayer - 1 month ago 12
Java Question

Why is my code for Codingbat String-2 EndOther not working?

I won't lie, this is sort of homework for my AP Computer Science class. But I talked to my teacher, and he couldn't figure it out either.

So I'm doing the Java CodingBat problem String-2 endOther here, and I don't know why my code isn't working properly.

The goal of the challenge is to determine if one string appears at the very end of the other string. If so, return true, otherwise return false.

Example: If the strings were "Hiabc" and "abc", it would return true, but "Hiabcx" and "bc" would return false because "bc" isn't at the end.
Note: Case does not matter.

My code works for all of the examples that it runs through, except for "other tests". I might have been able to figure out how to fix it, except I don't know what "other tests" it ran. So any help on this? Here's my code:

public boolean endOther(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a.contains(b) && a.indexOf(b) == a.length() - b.length()) {
return true;
} else if (b.contains(a) && b.indexOf(a) == b.length() - a.length()) {
return true;
} else {
return false;
}
}


Thanks!

Answer

I know that an answer to this question has already been posted, but as far as your original code goes, I think I have an idea of what went wrong. If the one of the "other tests" used a string such as "abc" and was compared with a string that had more than one occurrence of "abc" such as "Hiabcabc", then your code would fail even though "abc" is at the end of "Hiabcabc". The reason this happens is that indexOf() looks for the first occurrence of the parameter and returns the index of it. This would result in false negatives in tests that contained more than one occurrence of the smaller string.

Using substring() is probably the best solution to this problem as it would allow you to look specifically at the end of the string, however if you wanted to modify your code as little as possible, you could use lastIndexOf() as an alternative to indexOf(). This would result in your code passing all of the tests.

Here's your modified code:

public boolean endOther(String a, String b) {
  a = a.toLowerCase();
  b = b.toLowerCase();
  if (a.contains(b) && a.lastIndexOf(b) == a.length() - b.length()) {
    return true;
  } else if (b.contains(a) && b.lastIndexOf(a) == b.length() - a.length()) {
    return true;
  } else {
    return false; 
  }
}

And here's the Oracle docs page on indexOf() in case you want to do some more reading: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)