0

On a site called Codingbat.com I have been presented with the challenge of detecting whether a string ends in "ly" or not. I have thoroughly checked my code, but it doesn't seem to be working. When I input "ly" it detects perfectly fine, however, words such as "oddly" or "exactly" don't issue the true Boolean response as they should. Here is my code so far:

if (str.length() > 1) {
  String lastTwo = str.substring(str.length()-2, str.length());
  if (lastTwo == "ly") {
    return true;
  } else {
    return false;
  }
} else {
  return false;
}
  • You're comparing references, not objects. You need `lastTwo.equals("ly")`. – teppic Sep 11 '17 at 23:01
  • Java has a built in method String#endsWith `String s = "odly"; System.out.println(s.endsWith("ly"));` – baao Sep 11 '17 at 23:03

0 Answers0