It will not work for the case of doubleX("axxbb"). It should return true but gives false.
You have couple problems with your code:
if (str.substring(i) == "x") {
The String.substring(...)
method returns the portion of the string that starts at position i
. To quote the javadocs:
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
So if you do str.substring(1)
where str
is "axxbb"
then substring
would return "xxbb"
. I think you should instead use str.charAt(i)
which returns the character at that position. So your code should be:
if (str.charAt(i) == 'x') {
...
}
The 2nd conceptual problem is that strings cannot be compared with ==
. String
is an object and when objects are compared with ==
then you are comparing the reference of the object instead of its contents. To compare strings you should use string.equals("x")
. See this answer for more details.
But, again, you wanted to do str.charAt(i)
here.
Lastly, your code is going to have problems on the last character because you are string to do a str.charAt(i + 1)
which will throw a StringIndexOutOfBoundsException
. So the loop should be:
// subtract one from the length because we are looking for 2 x's in a row
for (int i = 0; i < str.length() - 1; i++) {
We go to str.length() - 1
because we are looking for 2 characters in a row.