簡體   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