[英]How can I get the sum of an array?
I'm trying to sum up all of the elements in an array.我试图总结数组中的所有元素。 What do I need to put in for blank space of
int i = ______;
我需要为
int i = ______;
空白输入什么int i = ______;
to make this work?使这项工作?
public static int sumArray(int [] A){
int sum = 0;
int i = ___________ ;
while(i>=0){
sum = sum + A[i];
i--;
}return sum;
}
I'm trying to sum up all of the elements in an array.
我试图总结数组中的所有元素。 What do I need to put in for blank space of 'int i = ______;'
我需要为'int i = ______;'的空格输入什么? to make this work?
使这项工作?
You should specify the size of array A
to i
by doing i = A.length - 1;
您应该通过执行
i = A.length - 1;
来指定数组A
到i
的大小i = A.length - 1;
. .
Alternatively, you can use a for
loop instead of while
.或者,您可以使用
for
循环而不是while
。
Here is the code snippet:这是代码片段:
public static int sumArray(int [] A){
int sum = 0;
for(int x : A) {
sum += x;
}
return sum;
}
To answer your question, you should set int i
to A.length - 1
.要回答您的问题,您应该将
int i
设置为A.length - 1
。 You want length - 1
because Arrays
are indexed at 0 which means using length
alone will cause you an IndexOutOfBoundsException
.您需要
length - 1
因为Arrays
的索引为 0,这意味着单独使用length
会导致您出现IndexOutOfBoundsException
。
Your method should look like this:您的方法应如下所示:
public static int sumArray(int[] A) {
int sum = 0;
int i = A.length - 1;
while (i >= 0) {
sum = sum + A[i];
i--;
}
return sum;
}
However , you can do this in much more cleaner ways.但是,您可以以更简洁的方式执行此操作。
1) Using Java 8 you can use IntStream
like so: 1) 使用 Java 8,您可以像这样使用
IntStream
:
public static int sumArray(int[] A) {
return IntStream.of(A).sum();
}
2) You can use a for
loop: 2)您可以使用
for
循环:
public static int sumArray(int[] A) {
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
return sum;
}
3) You can use an enhanced for
loop: 3) 您可以使用增强的
for
循环:
public static int sumArray(int[] A) {
int sum = 0;
for(int i : A){
sum += i;
}
return sum;
}
You've already written the code to get the sum.您已经编写了获取总和的代码。
i
just needs to start out at A.length
. i
只需A.length
开始。
There are many other ways to get the sum: using an enhanced "for each" loop;还有许多其他方法可以获得总和:使用增强的“for each”循环; using
IntStream.of(A).sum()
;使用
IntStream.of(A).sum()
; other library methods.其他库方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.