gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:59:02 25 4
gpt4 key购买 nike

我正在尝试让 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你应该没有问题。

关于java - 你如何在java中找到数组中某些元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29284268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com