In most languages that use it, it represents the modulus operation.
In APEX, you use Math.Mod()
if (Math.Mod(x, 2) == 0) {
system.debug(x + ' is even');
}
APEX Expression Operators Reference shows that there is no definition of a % operator.
Videos
As of Spring 19 (and all prior versions), we only have mod(Integer, Integer) and mod(Long, Long). There is no known information of when, or if, we might get a built in for Decimal or Double values.
In case anyone happens upon this page, one way to do this is (assuming someDecimal is non-null):
Decimal remainder = someDecimal - someDecimal.round(RoundingMode.DOWN);
I see 3 problems:
The
ifis wrong. You check if the loop counter is odd, even, odd, even... What you need isif(Math.mod(arr[i], 2) == 0). Use the value at that index, not just the index itself.The first two system.debugs - I think you intended them to display the
odd/evenvariable, not the loop counteri. Probably copy-paste error?System.debug('even numbers -- ' + even);should work better?Not terribly evil but weird - in bottom system.debugs you want to just display
even, noteven++. As it's end of the function it doesn't matter much but if you'd be returning this value and using it further in the program - subtle, nasty error.
@eyescream, I have edited my code as you suggested. In line
system.debug('even numbers -- ' +arr[i]);
I have used arr[i] to show which value is odd / even
public class even_odd_11{
public void check_number()
{
integer i, odd = 0, even = 0;
integer[] arr = new integer[]{2,41,51,61};
for (i=0; i<arr.size(); i++)
{
if(Math.mod(arr[i], 2) == 0)
{
even++;
system.debug('even numbers -- ' +arr[i]);
}
else
{
odd++;
system.debug('odd numbers -- ' +arr[i]);
}
}
system.debug('Total even numbers are ' +even);
system.debug('Total odd numbers are ' +odd);
system.debug(' size of array -- ' +arr.size());
}
}
Now my code is working fine. Thanks