简体   繁体   中英

How to compare specific elements of an array in java

I'm trying to compare elements of an array of ints 8 elements long (array[]) add up the elements in sets of 2, then divide by 2 for the avg, eg array[0] + array[1] / 2 and assign the result to a new array 4 elements long.. Specifically, I want to compare them in sets of 2 to see if either / or both are less than 40, if either is less than 40, I add them both up and divide by 2 for the average, and assign the array with the minimum out of (40, array[i]).. however if they are both above 40 I still add both elements and divide by 2 but assign the array element[i] with the number I get, not bothering with a minimum calculation

Heres what I have so far

   for (int i = 0; i < array.length ; i++)
    {
        if (array[i] < 40 )
        {
            array2[j] = Math.min(35, array2[j]);
        }
    }

The if statement is correct I think, but the boolean argument is far from it. Array[] = the original 8 element array... array2[] = the calculated and averaged array 4 elements long. Many thanks

Is this what you mean? Hopefully I understood the question.

for (int j = 0; j < array2.length; j++)
{
    double avg = (array[2 * j] + array[2 * j + 1]) / 2;
    if (array[2 * j] < 40 || array[2 * j + 1] < 40)
    {
        array2[j] = Math.min(avg, 40);
    } else {
        array2[j] = avg;
    }
}

I think this captures the logic you described(?)

int[] test = {
    22,44,
    52,36,
    35,41,
    63,24
};
double[] newarr = new int[test.length/2];

for (int i = 0; i < newarr.length; i++){
    newarr[i] = (test[i*2] + test[i*2+1]) / 2;
}

Gives:

[33.0, 44.0, 38.0, 43.5]

Correct?

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