salesforceapexapex-code

apex array result is not showing as expected


I'm writing apex (salesforce) code to count total even and odd numbers in an array. Instead of counting numbers in the array, it is showing me numbers from array size and evaluates them.

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 -- ' +i);
        }
        
    else
    {
        odd++;
        system.debug('odd numbers -- ' +i);
    }
            
    }
    system.debug('Total even numbers are ' +even);
    system.debug('Total odd numbers are ' +odd);
    system.debug(' size of array -- ' +arr.size());
    
}

}

According to the code, I need to count total even and odd numbers and display those numbers as mentioned in array. For e.g.

total even number are 1 even numbers -- 2

total odd numbers are- 3 odd numbers -- 41,51,61

Please help me with the code, where I'm doing wrong.

Result showing

Thank You


Solution

  • I see 3 problems:

    1. The if is wrong. You check if the loop counter is odd, even, odd, even... What you need is if(Math.mod(arr[i], 2) == 0). Use the value at that index, not just the index itself.

    2. The first two system.debugs - I think you intended them to display the odd/even variable, not the loop counter i. Probably copy-paste error?

      System.debug('even numbers -- ' + even); should work better?

    3. Not terribly evil but weird - in bottom system.debugs you want to just display even, not even++. 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.