tags:

views:

781

answers:

5
public boolean catDog(String str)
{
   int count = 0;

   for (int i = 0; i < str.length(); i++)
   {
      String sub = str.substring(i, i+1);

      if (sub.equals("cat") && sub.equals("dog"))
         count++;
   }

   return count == 0;
}

There's my code for catDog, have been working on it for a while and just cannot find out what's wrong. Help would be much appreciated!*/

EDIT- I want to Return true if the string "cat" and "dog" appear the same number of times in the given string.

+6  A: 

One problem is that this will never be true:

if (sub.equals("cat") && sub.equals("dog"))

&& means and. || means or.

However, another problem is that your code looks like your are flailing around randomly trying to get it to work. Everyone does this to some extent in their first programming class, but it's a bad habit. Try to come up with a clear mental picture of how to solve the problem before you write any code, then write the code, then verify that the code actually does what you think it should do and that your initial solution was correct.

EDIT: What I said goes double now that you've clarified what your function is supposed to do. Your approach to solving the problem is not correct, so you need to rethink how to solve the problem, not futz with the implementation.

RossFabricant
A: 
String sub = str.substring(i, i+1);

The above line is only getting a 2-character substring so instead of getting "cat" you'll get "ca" and it will never match. Fix this by changing 'i+1' to 'i+2'.

Edit: Now that you've clarified your question in the comments: You should have two counter variables, one to count the 'dog's and one to count the 'cat's. Then at the end return true if count_cats == count_dogs.

yjerem
+3  A: 

Here's a critique since I don't believe in giving code for homework. But you have at least tried which is better than most of the clowns posting homework here.

  • you need two variables, one for storing cat occurrences, one for dog, or a way of telling the difference.
  • your substring isn't getting enough characters.
  • a string can never be both cat and dog, you need to check them independently and update the right count.
  • your return statement should return true if catcount is equal to dogcount, although your version would work if you stored the differences between cats and dogs.

Other than those, I'd be using string searches rather than checking every position but that may be your next assignment. The method you've chosen is perfectly adequate for CS101-type homework.

It should be reasonably easy to get yours working if you address the points I gave above. One thing you may want to try is inserting debugging statements at important places in your code such as:

System.out.println(
    "i = " + Integer.toString (i) +
    ", sub = ["+sub+"]" +
    ", count = " + Integer.toString(count));

immediately before the closing brace of the for loop. This is invaluable in figuring out what your code is doing wrong.

Here's my ROT13 version if you run into too much trouble and want something to compare it to, but please don't use it without getting yours working first. That doesn't help you in the long run. And, it's almost certain that your educators are tracking StackOverflow to detect plagiarism anyway, so it wouldn't even help you in the short term.

Not that I really care, the more dumb coders in the employment pool, the better it is for me :-)

choyvp obbyrna pngQbt(Fgevat fge) {
    vag qvssrerapr = 0;
    sbe (vag v = 0; v < fge.yratgu() - 2; v++) {
        Fgevat fho = fge.fhofgevat(v, v+3);
        vs (fho.rdhnyf("png")) {
            qvssrerapr++;
        } ryfr {
            vs (fho.rdhnyf("qbt")) {
                qvssrerapr--;
            }
        }
    }
    erghea qvssrerapr == 0;
}
paxdiablo
rot13 solution, awesome.
John Gardner
Indeed. Took me a while to decode qvssrerapr in my head, but this is definitely the code I would have written (barring the trivial difference between `ryfr { vs` and `ryfr vs`
Bill Michell
In your head? That's impressive. I just used an online translator to make it :-)
paxdiablo
A: 

Another thing to note here is that substring in Java's built-in String class is exclusive on the upper bound.

That is, for String str = "abcdefg", str.substring( 0, 2 ) retrieves "ab" rather than "abc." To match 3 characters, you need to get the substring from i to i+3.

Stefan Kendall
A: 

My code for do this:

public boolean catDog(String str) {

    if ((new StringTokenizer(str, "cat")).countTokens() ==
        (new StringTokenizer(str, "dog")).countTokens()) {

     return true;
    }
    return false;
}

Hope this will help you

EDIT: Sorry this code will not work since you can have 2 tokens side by side in your string. Best if you use countMatches from StringUtils Apache commons library.

SourceRebels