|
-- Posted by xren at 12:11 pm on April 3, 2008
Can anyone help me with this simple for loop, that just isn't working for me? If you would like to use the website that I'm doing this on, it is on javabat.com, String2 -> catDog. 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; } } Any (useful) help is appreciated =)
-- Posted by Whuppee at 4:16 pm on April 4, 2008
Why it doesn't work: for(int i= 0; i < (len-2); i++) An i of 0 is not less than a length of (less than or equal to) 2 minus 2. 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? Misc. Efficiency:- Declare String sub; before / outside of the loop.
The optimizer should resolve this for you, but it still shouldn't be (re)declared every pass through the loop. - Your two ifs should be an if/else if.
If the string is "cat", it can't also be "dog". - As above, determine if cat == dog after / outside of the loop.
-- Posted by xren at 10:18 pm on April 7, 2008
Thanks a lot for the help. 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.
-- Posted by JudeLaurence at 12:05 pm on May 1, 2008
My CS teacher makes us do these quizzes too but when I did that particular one, I found it easier to use the indexOf method with the second fromIndex parameter and just keep narrowing the string. And instead of keeping track of the numbers of cats and dogs, I used a single counter and incremented it with every cat occurence, and decremented with every dog occurence. That's all a matter of taste though.
|