如何在java中找到数组中某些元素的总和

时间:2015-03-26 16:47:47

标签: java

我试图让sumSection总结一个跑步者所要求的元素,但不确定如何做到这一点?

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;
    }
}

这是跑步者:

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));

    }
}

我正在尝试获取阵列0-3中位置的总和。我已经在java中尝试了所有我知道但不明白如何使用sumSection

获取数组中0-3的总和

3 个答案:

答案 0 :(得分:3)

您可以使用Java 8 Streams:

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

这是从startstop(不包括),所以如果你有:

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

它有点像这样:

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

请确保start < stopstop <= numArray.length并且您应该没有任何问题。

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您需要其他类型的循环而不是:

for (int i : numArray)

更好的方法是:

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