繁体   English   中英

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

[英]How do you find the sum of certain elements in an array in 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的总和

您可以使用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并且应该没有问题。

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

您需要另一种类型的循环,而不是:

for (int i : numArray)

更好的方法是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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