Skip to content
Advertisement

Any comparasion condition returns bad value

I struggle with very strange behaviour while trying to compare two ints but first things first. Here is my method inside the class:

JavaScript

The whole class doesn’t really matter here – it only holds ArrayList<String>. I need to return every 3rd element in a tree and everything goes well until it’s time to compare current counter value. It returns true everytime. I’m sure of it becouse while testing it’s adding to the Tree every single element of collection. I’ve tried using compareTo(), equalsTo(), valueOf() and intValue() but nothing helps.

EDIT. I’ve change code to the class view – maybe something else is cousing the error?

Here is test i’m trying to pass

JavaScript

Advertisement

Answer

“I need to return every 3rd element in a tree…” this description screams for the modulo % operator.

If you want to enter an if-condition on every 3rd iteration then you can check this with the following condition: counter % 3 == 0. You don’t need to subtract anything at all.

How does % work?

Put simply: The modulo operator returns the result of a division.

Example:

JavaScript

Note:

JavaScript

You use counter % 2 == 0. This will return true for the second element. Afterwards you set counter = -1 because you intend to get every 3rd element. However, this does not work.

Here’s the reason why:

JavaScript

As you can see, every time your counter reaches the value 0 the if-condition will result in true regardless of the divisor. That’s why you use % 3.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement