-1

 String[] splitArray = str.split("(?<=[dog,cat])");

 int dogCounter = 0;
 int catCounter = 0;

 for(int i = 0; i < splitArray.length; i++) {

   if (splitArray[i] == "dog") {

     dogCounter += 1;
   }

   else if (splitArray[i] == "cat") {

     catCounter += 1;
   }
 }

 if (dogCounter == catCounter) {

   return true;
 }

 else {

   return false;
 }
}

So this code essentially takes the string provided when running the function, and splits it at dog and cat but without actually removing dog or cat from the string, then assigns this to an array, loops through the array determining if any of the items equal cat or dog and adding them to their respective variables if so, then if cat and dog are both in the sting an equal amount of times it is supposed to return true, and if not, return false. But it always returns true no matter what.

2 Answers2

1

Use equals method for string comparison.

splitArray[i].equals("dog")

While the objects you're comparing are never the same, cat and dog counter will always be 0.

At the end the result is, that both counter are 0 and this leads to returning true

Manuel
  • 1,928
  • 2
  • 16
  • 26
  • I did this for all three comparison statements but on the last one that compares both counter variables it says "int cannot be dereferenced" – StoneColdCoder Mar 17 '20 at 20:42
  • @StoneColdCoder you really need to understand a difference between primitive types and objects. Strings are objects and you should use `equals` to compare them unless you're after reference equality. For primitives however, you can't use `equals` - you should use `==`. More details here https://en.wikibooks.org/wiki/Java_Programming/Comparing_Objects – Dmitry Pisklov Mar 17 '20 at 21:08
0

I believe the issue is you are using == to compare strings. This doesn't always work in Java, and it is best to avoid it altogether and use the .equals() method. If you print out the values of dogCounter and catCounter they will probably both be 0

Tim Winters
  • 159
  • 2
  • 7
  • I did that for all three comparison statements but now on the if statement seeing if both variables are equal it says "int cannot be dereferenced" – StoneColdCoder Mar 17 '20 at 20:38
  • You can use `==` to compare `dogCounter` and `catCounter` because they're `int`s. `==` can be used to compare any [primitive](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) – Tim Winters Mar 17 '20 at 20:57