Home > Enterprise >  what type of other tests will cause an error?
what type of other tests will cause an error?

Time:10-05

On codingbat string-2, the question end other asks to return true if either a appears at the end of b or if b appears at the end of a. Upon finishing my code, the "other tests" is the only test with an error. What am I missing?

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

"other tests" is negative

CodePudding user response:

b might appear multiple times in a (and vice versa). However, indexOf only returns the first occurrence, so your index checks can fail.

Use String#endsWith instead.

return a.endsWith(b) || b.endsWith(a);
  •  Tags:  
  • java
  • Related