-1
public boolean xyzThere(String str) {
  for (int i=0; i < str.length()-3; i++){
    if (str.substring(i+1, i+4) == "xyz" && str.charAt(i) != '.'){
      return true;
    }
  }
  return false;
}

The above function always returns false, cannot work out why. I'm going through the codingbat.com Java exercises, here is the brief:

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

Can anyone help?

1 Answers1

1

You cannot use == for String comparison. It will compare the references of the strings.

public static boolean xyzThere(String str) {
      for (int i=0; i < str.length()-3; i++){
        if ("xyz".equalsIgnoreCase(str.substring(i+1, i+4)) && str.charAt(i) != '.'){
          return true;
        }
      }
      return false;
}

Try this one.

Neero
  • 226
  • 2
  • 7
  • 23