简体   繁体   中英

How do you find the sum of certain elements in an array in java

I'm trying to get sumSection to summarize the element that a runner calls on but am unsure on how to do it?

package com.company;

public class processser
{
    //instance variables and constructors could be present, but are not necessary

    //sumSection will return the sum of the numbers
    //from start to stop, not including stop
    public static int sumSection(int[] numArray, int start, int stop)
    {
        int sum = 0;
        {
            for (int i : numArray)
                sum += i;
        }
        return sum ;
    }

    //countVal will return a count of how many times val is present in numArray
    public static int countVal(int[] numArray, int val)
    {
        int count = 0;
        for (int item : numArray)
        {
            if (item == val)
            {
                count = count + 1;
            }
        }
        return count;
    }
}

Here is the runner:

package com.company;

import static java.lang.System.*;
import java.lang.Math;
import java.util.Arrays;

public class Main
{
    public static void main(String args[])
    {
        int[] theRay = {2,4,6,8,10,12,8,16,8,20,8,4,6,2,2};

        out.println("Original array : "+ Arrays.toString(theRay));

        out.println("Sum of 0-3: " + processser.sumSection(theRay, 0, 3));

    }
}

I'm trying to get the sum of the positions in my array 0-3. I've tried all I know in java but don't understand how to get the sum of 0-3 in the array using sumSection

You could use Java 8 Streams:

static int sumSection(int[] numArray, int start, int stop) {
    return IntStream.range(start, stop).map(i -> numArray[i]).sum();
}

This goes from start to stop (exclusive), so if you have:

int[] theRay = {2,4,6,8,10,12,8,16,8,20,8,4,6,2,2};
sumSection(theRay, 0, 3);

It would work somewhat like this:

IntStream.range(0, 3) -> [0, 1, 2]
[0, 1, 2].map(i -> numArray[i]) -> [2, 4, 6]
[2, 4, 6].sum() -> 12

Just be sure that start < stop and stop <= numArray.length and you should have no problems.

for (int i = start; (i < numArray.length) && (i <= stop); i++) {
    sum += numArray[i];
}

You need another type of loop instead of:

for (int i : numArray)

A better approach would be:

int sum = 0;
if(stop <= array.length && start < stop) {
    for(int i = start; i < stop; i++) {
        sum += array[i];
    }
}

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