-6

I want to compare values and execute some condition if some of the values are found. In Java I tried using this code:

if(item.getLenght().compareTo(BigDecimal.valueOf(50))
                        || item.getSocre().compareTo(BigDecimal.valueOf(500))
                        || item.getAge().compareTo(BigDecimal.valueOf(5000)))
                        {
                        ....... do some action
}

But I get error Operator '||' cannot be applied to 'int', 'int'

What is the proper way to implement this check?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 2
    Perhaps you mean `.equals` instead of `.compareTo`? What *integer* results from `compareTo` would you expect to mean "execute the body of the if statement", and what *integer* results would you expect to mean "don't execute the body of the if statement"? – Jon Skeet Feb 04 '23 at 11:03
  • 1
    @JonSkeet Not a good idea to compare BigDecimals with equals – TT. Feb 04 '23 at 11:03
  • 1
    @TT.: Care to elaborate? We don't know what the OP is trying to achieve. I agree there are cases where it's not desirable (where 50 and 50.0 should be seen as equivalent, which they're not under equals) but I wouldn't make a blanket statement like that - particularly with no further explanation. – Jon Skeet Feb 04 '23 at 11:05
  • 1
    @JonSkeet The user is trying to establish if the numbers represented by the BigDecimal objects are equal. But using equals is a gotcha, as `new BigDecimal( "1.00" )` and `new BigDecimal( "1" )` are not equal (because the one has two decimal digits, the other doesn't). Using compare does a number comparison, where 1.00 and 1 are effectively equal and `compareTo` returns 0. But you knew that already it seems. And there is no real world case I ever encountered where using equals to compare BigDecimals is what is really intended. – TT. Feb 04 '23 at 17:50

2 Answers2

3

The method BigDecimal#compareTo(BigDecimal) returns int, not boolean, so the operator || won't work.

You need to change your code a bit:

if (item.getLenght().compareTo(BigDecimal.valueOf(50)) == 0
    || item.getSocre().compareTo(BigDecimal.valueOf(500)) == 0
    || item.getAge().compareTo(BigDecimal.valueOf(5000)) == 0) {

    // do something funny
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

Compare to method does not return boolean, it returns int. Here is the spec https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal) So if you want to check if length is equal to 50 you need to write:

item.getLenght().compareTo(BigDecimal.valueOf(50)) == 0

The same applies to all other conditions in your code.

antonio_s87
  • 127
  • 2