简体   繁体   中英

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 eg

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.

结果显示

Thank You

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.

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM