1

The goal is to have it count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

See http://codingbat.com/prob/p194667 I can't seem to figure out why its not working

    int countXX(String str) {
        int f = 0;
        for (int i = 0; i < str.length(); i++){
            if (!str.substring(i+1).isEmpty()){
                if (str.substring(i) == "x" && str.substring (i+1) == "x") {
                    f++;
                }
            }
        }
        return f;  
    }
zellus
  • 9,617
  • 5
  • 39
  • 56
  • This is a common mistake by starters. Be careful. – Lion May 03 '13 at 21:51
  • While it's wrong to compare string values with `==`, this question is more about the misuse of `substring` to extract a character. – rgettman May 03 '13 at 21:52
  • 1
    I have voted to reopen this question; it's not a duplicate of any common "==" vs. "equals" string comparison problem. – rgettman May 03 '13 at 21:59

6 Answers6

4

Don't use == to compare strings; use equals().

int countXX(String str) {
    int f = 0;
    for (int i = 0; i < str.length(); i++) {
        if (!str.substring(i+1).isEmpty()) {
            if (str.substring(i).equals("x") && str.substring(i+1).equals("x")) {
                f++;
            }
        }
    }
    return f;  
}

I think this code will still have a problem when i equals the length of the string minus 1 and you try to access the character at (i+1).

duffymo
  • 305,152
  • 44
  • 369
  • 561
4

The substring method with one argument doesn't get just that character at that position, it gets everything from that position through to the end of the string. Use charAt to get the character at that position, and compare it with == with the character literal 'x', not with the String "x".

rgettman
  • 176,041
  • 30
  • 275
  • 357
4

Don't use substring for indexing chars.

int countXX(String str) {
   int f = 0;
   for (int i = 0; i < str.length()-1; i++) {
      if( str.charAt(i) == 'x' && str.charAt(i+1) == 'x' ) {
         f++;
      }
   }
   return f;  
}
Mirco Ellmann
  • 983
  • 7
  • 8
2

Three reasons:

  1. substring() returns the whole string (so starting from "i" to the end of the string, and not only one letter).
  2. Compare with .equals() and not ==
  3. "i" should end at str.length() - 1
Michal Borek
  • 4,584
  • 2
  • 30
  • 40
1

Use the string's 'equals' method in stead of == :

int countXX(String str) {
    int f = 0;
    for (int i = 0; i < str.length(); i++){
    if (!str.substring(i+1).isEmpty()){
    if (str.substring(i).equals("x") && str.substring (i+1).equals("x")) {
    f++;}}}
    return f;  
    }
Toverbal
  • 256
  • 3
  • 14
0
int countXX(String str) {
    int f = 0;
    for (int i = 0; i < str.length() - 1; i++){
        if (str.substring(i, i + 2).equals("xx")) {
            f++;
        }
    }
    return f;  
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138