0

My goal, in Java, is to return true of the number of occurrences of "cat" in a string is equal to the number of occurrences of "dog".

public boolean catDog(String str) {
   int matches = 0, matches2 = 0;
   for(int i = 0; i < str.length()-2; ++i)
   {
     if(str.substring(i,i+3)=="cat")++matches;
     if(str.substring(i,i+3)=="dog")++matches2;
   }
  if(matches==matches2)return true;
  return false;
}

It always returns true(probably not incrementing counters) unless str is exactly "dog" or "cat". Why?

John Targaryen
  • 1,109
  • 1
  • 13
  • 29

3 Answers3

1

Ah, messed around a bit and found that you need .equals("cat"), not ==.

John Targaryen
  • 1,109
  • 1
  • 13
  • 29
  • 1
    you might also use `.toLowerCase()` otherwise you wont find "Cats" or "DOGS!". – ug_ Sep 27 '14 at 22:26
0

Because you are comparing strings with ==, while you should use .equals(..).

In addition there is no need to scan the strings one character each. Just use

public int indexOf(String str, int fromIndex)

So that you can skip many more characters per step. Eg:

for (int i = 0; i < str.length(); /* do nothing */)
{
  int x == str.indexOf("dog", 0);
  if (x == -1)
  {
    // no more occurrences
  }
  else
  {
    i = x + "dog".length();
  }
}
Jack
  • 131,802
  • 30
  • 241
  • 343
0

Your idea seems to be right but comparisons of strings used to be tricky. Try

if(str.substring(i,i+3).equals("cat")) ++matches;

Greetings Ralf

lilleGauss
  • 68
  • 7