But for those who would rather not visit the site, please look at my code and tell me what I'm missing, because it really is driving me crazy.
Problem: Return true if the string "cat" and "dog" appear the same number of times in the given string.
My Code:
public boolean catDog(String str) { boolean result = false; int cat = 0; int dog = 0; int len = str.length(); for(int i = 0; i <(len-2);i++) { String sub = str.substring(i, i+3); if (sub.equals("cat")) cat ++; if (sub.equals("dog")) dog ++; if (cat != dog) result = false; else result = true; } return result; } }
boolean result = false; int cat = 0; int dog = 0; int len = str.length();
for(int i = 0; i <(len-2);i++) {
String sub = str.substring(i, i+3); if (sub.equals("cat")) cat ++; if (sub.equals("dog")) dog ++;
if (cat != dog) result = false; else result = true; } return result;
}
Any (useful) help is appreciated =)
That's all a matter of taste though.
It makes a lot more sense, I just always miss the little details every now and then and then I go crazy.
I appreciate the help. It works btw.
Result is initialized to false, and only modified within the loop.
Since the loop will never run for lengths less than or equal to 2, the result can only be false.
For a simple fix, consider..
If the purpose of the loop is to count how many times both "dog" and "cat" occur..
Is there any point to knowing if they've occured the same amount of times, or not, when you're not done counting?
The optimizer should resolve this for you, but it still shouldn't be (re)declared every pass through the loop.
If the string is "cat", it can't also be "dog".