I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math
class for this.
我在Java中找到一个数组中所有整数的和的问题。我在数学课上找不到任何有用的方法。
23 个解决方案
#1
179
In java-8 you can use streams:
在java-8中,可以使用流:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
输出:
The sum is 150.
金额是150。
It's in the package java.util.stream
它在包java.util.stream中。
import java.util.stream.*;
#2
29
This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.
这是在标准Java API中不存在的简单事情之一。写自己的东西很容易。
Other answers are perfectly fine, but here's one with some for-each syntactic sugar.
其他的答案都是完美的,但这里有一种对每种句法的糖。
int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : someArray)
sum += i;
Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.
另外,在Java 7语言规范中还显示了数组求和的一个例子。该示例来自第10.4节-数组访问。
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
#3
21
If you're using Java 8, the Arrays
class provides a stream(int[] array)
method which returns a sequential IntStream
with the specified int
array. It has also been overloaded for double
and long
arrays.
如果您使用的是Java 8,那么数组类提供了一个流(int[]数组)方法,该方法返回一个带有指定的int数组的序列IntStream。它还被重载了两倍和长数组。
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method stream(int[] array, int startInclusive, int endExclusive)
which permits you to take a specified range of the array (which can be useful) :
它还提供了一个方法流(int[]数组,int startinclude, int endExclusive),它允许您使用数组的指定范围(这是有用的):
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T
. So you can per example have a String
which contains numbers as an input and if you want to sum them just do :
最后,它可以取一个t类型的数组,每个例子都有一个字符串包含数字作为输入,如果你想把它们加起来就行了
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
#4
17
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
你不能。其他语言有一些方法,比如PHP中的array_sum(),但Java没有。
Just..
只是. .
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
#5
13
The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.
我要添加到以前的解决方案的唯一要点是,我将使用一段很长的时间来累积总数,以避免任何溢出的值。
int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;
for (int i : someArray)
sum += i;
#6
12
In Apache Math : There is StatUtils.sum(double[] arr)
在Apache数学中:有StatUtils。总和(double[]arr)
#7
4
IMHO a sum function would seem a good fit to extend the Arrays class where fill, sort, search, copy, & equals live. There are a lot of handy methods hiding in the javadocs so it is a fair question when porting Fortran to java to ask before rolling our own helper method. Search through the huge javadoc index for "sum", "add" and any other keyword you might think of. You might suspect certainly someone has already done this for primitive types int, float, double, Integer, Float, Double? No matter how simple, it is always good to check. Keep the code as simple as possible and don't reinvent the wheel.
IMHO的求和函数似乎很适合扩展数组类,其中填充、排序、搜索、复制和等于live。在javadocs中隐藏了许多方便的方法,所以在将Fortran移植到java之前,在滚动我们自己的助手方法之前,这是一个很好的问题。通过巨大的javadoc索引搜索“sum”、“add”以及您可能想到的任何其他关键字。你可能会怀疑有人已经这样做了,对于原始类型int, float, double, Integer, float, double ?无论多么简单,检查总是好的。保持代码尽可能简单,不要重新发明*。
#8
4
In Java 8
在Java 8
Code:
代码:
int[] array = new int[]{1,2,3,4,5};
int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
System.out.println("The summation of array is " + sum);
System.out.println("Another way to find summation :" + IntStream.of(array).sum());
Output:
输出:
The summation of array is 15
Another way to find summation :15
Explanation:
解释:
In Java 8
, you can use reduction concept to do your addition.
在Java 8中,可以使用reduce概念来做加法。
阅读所有关于减少
#9
3
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
#10
3
I like this method personally. My code style is a little weird.
我个人喜欢这种方法。我的代码风格有点奇怪。
public static int sumOf(int... integers) {
int total = 0;
for (int i = 0; i < integers.length; total += integers[i++]);
return total;
}
Pretty easy to use in code:
在代码中很容易使用:
int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1);
sumOf(1, 2, 3);
sumOf(numbers);
#11
2
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
你必须自己动手。你从0开始。然后,考虑数组中的每个整数,将其添加到总数中。然后当你没有整数时,就有了和。
If there were no integers, then the total is 0.
如果没有整数,则总数为0。
#12
2
int sum = 0;
for (int i = 0; i < myArray.length; i++)
sum += myArray[i];
}
#13
2
There are two things to learn from this exercise :
从这个练习中可以学到两件事:
You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop. You need to store the result of the summation in an accumulator. For this, you need to create a variable.
您需要以某种方式遍历数组元素——您可以用for循环或while循环来完成此操作。您需要将求和结果存储在一个累加器中。为此,您需要创建一个变量。
int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
#14
2
You can make your code look better like this:
您可以让您的代码看起来更好:
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
#15
1
define a sum variable = 0
for each number in array:
sum = sum + number
#16
1
public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}
//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}
//To display the sum
System.out.println("The sum is :"+sum);
}
}
#17
1
There is a sum() method in underscore-lodash library.
在低分数-lodash库中有一个sum()方法。
Code example:
代码示例:
import com.github.underscore.lodash.$;
public class Main {
public static void main(String[] args) {
int sum = $.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
#18
1
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
我们可以使用用户定义的函数。初始化sum变量等于零。然后遍历数组并添加元素sum。然后更新sum变量。
Code Snippet :
代码片段:
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
#19
1
I use this:
我用这个:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
#20
0
There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.
对于这种事情,数学课上没有“方法”。它不像一个平方根函数或者类似的东西。
You just need to have a variable for the sum and loop through the array adding each value you find to the sum.
你只需要有一个变量来求和,并在数组中循环,将你找到的每个值相加。
#21
0
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
#22
0
As of Java 8 The use of lambda expressions have become available.
在Java 8中,lambda表达式的使用变得可用。
See this:
看到这个:
int[] nums = /** Your Array **/;
Compact:
简洁:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
喜欢:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.
返回或打印。
#23
-1
public class AddDemo {
public static void main(String[] args) {
ArrayList <Integer>A = new ArrayList<Integer>();
Scanner S = new Scanner(System.in);
System.out.println("Enter the Numbers: ");
for(int i=0; i<5; i++){
A.add(S.nextInt());
}
System.out.println("You have entered: "+A);
int Sum = 0;
for(int i=0; i<A.size(); i++){
Sum = Sum + A.get(i);
}
System.out.println("The Sum of Entered List is: "+Sum);
}
}
#1
179
In java-8 you can use streams:
在java-8中,可以使用流:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
输出:
The sum is 150.
金额是150。
It's in the package java.util.stream
它在包java.util.stream中。
import java.util.stream.*;
#2
29
This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.
这是在标准Java API中不存在的简单事情之一。写自己的东西很容易。
Other answers are perfectly fine, but here's one with some for-each syntactic sugar.
其他的答案都是完美的,但这里有一种对每种句法的糖。
int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : someArray)
sum += i;
Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.
另外,在Java 7语言规范中还显示了数组求和的一个例子。该示例来自第10.4节-数组访问。
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
#3
21
If you're using Java 8, the Arrays
class provides a stream(int[] array)
method which returns a sequential IntStream
with the specified int
array. It has also been overloaded for double
and long
arrays.
如果您使用的是Java 8,那么数组类提供了一个流(int[]数组)方法,该方法返回一个带有指定的int数组的序列IntStream。它还被重载了两倍和长数组。
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method stream(int[] array, int startInclusive, int endExclusive)
which permits you to take a specified range of the array (which can be useful) :
它还提供了一个方法流(int[]数组,int startinclude, int endExclusive),它允许您使用数组的指定范围(这是有用的):
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T
. So you can per example have a String
which contains numbers as an input and if you want to sum them just do :
最后,它可以取一个t类型的数组,每个例子都有一个字符串包含数字作为输入,如果你想把它们加起来就行了
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
#4
17
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
你不能。其他语言有一些方法,比如PHP中的array_sum(),但Java没有。
Just..
只是. .
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
#5
13
The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.
我要添加到以前的解决方案的唯一要点是,我将使用一段很长的时间来累积总数,以避免任何溢出的值。
int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;
for (int i : someArray)
sum += i;
#6
12
In Apache Math : There is StatUtils.sum(double[] arr)
在Apache数学中:有StatUtils。总和(double[]arr)
#7
4
IMHO a sum function would seem a good fit to extend the Arrays class where fill, sort, search, copy, & equals live. There are a lot of handy methods hiding in the javadocs so it is a fair question when porting Fortran to java to ask before rolling our own helper method. Search through the huge javadoc index for "sum", "add" and any other keyword you might think of. You might suspect certainly someone has already done this for primitive types int, float, double, Integer, Float, Double? No matter how simple, it is always good to check. Keep the code as simple as possible and don't reinvent the wheel.
IMHO的求和函数似乎很适合扩展数组类,其中填充、排序、搜索、复制和等于live。在javadocs中隐藏了许多方便的方法,所以在将Fortran移植到java之前,在滚动我们自己的助手方法之前,这是一个很好的问题。通过巨大的javadoc索引搜索“sum”、“add”以及您可能想到的任何其他关键字。你可能会怀疑有人已经这样做了,对于原始类型int, float, double, Integer, float, double ?无论多么简单,检查总是好的。保持代码尽可能简单,不要重新发明*。
#8
4
In Java 8
在Java 8
Code:
代码:
int[] array = new int[]{1,2,3,4,5};
int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
System.out.println("The summation of array is " + sum);
System.out.println("Another way to find summation :" + IntStream.of(array).sum());
Output:
输出:
The summation of array is 15
Another way to find summation :15
Explanation:
解释:
In Java 8
, you can use reduction concept to do your addition.
在Java 8中,可以使用reduce概念来做加法。
阅读所有关于减少
#9
3
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
#10
3
I like this method personally. My code style is a little weird.
我个人喜欢这种方法。我的代码风格有点奇怪。
public static int sumOf(int... integers) {
int total = 0;
for (int i = 0; i < integers.length; total += integers[i++]);
return total;
}
Pretty easy to use in code:
在代码中很容易使用:
int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1);
sumOf(1, 2, 3);
sumOf(numbers);
#11
2
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
你必须自己动手。你从0开始。然后,考虑数组中的每个整数,将其添加到总数中。然后当你没有整数时,就有了和。
If there were no integers, then the total is 0.
如果没有整数,则总数为0。
#12
2
int sum = 0;
for (int i = 0; i < myArray.length; i++)
sum += myArray[i];
}
#13
2
There are two things to learn from this exercise :
从这个练习中可以学到两件事:
You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop. You need to store the result of the summation in an accumulator. For this, you need to create a variable.
您需要以某种方式遍历数组元素——您可以用for循环或while循环来完成此操作。您需要将求和结果存储在一个累加器中。为此,您需要创建一个变量。
int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
#14
2
You can make your code look better like this:
您可以让您的代码看起来更好:
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
#15
1
define a sum variable = 0
for each number in array:
sum = sum + number
#16
1
public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}
//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}
//To display the sum
System.out.println("The sum is :"+sum);
}
}
#17
1
There is a sum() method in underscore-lodash library.
在低分数-lodash库中有一个sum()方法。
Code example:
代码示例:
import com.github.underscore.lodash.$;
public class Main {
public static void main(String[] args) {
int sum = $.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
#18
1
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
我们可以使用用户定义的函数。初始化sum变量等于零。然后遍历数组并添加元素sum。然后更新sum变量。
Code Snippet :
代码片段:
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
#19
1
I use this:
我用这个:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
#20
0
There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.
对于这种事情,数学课上没有“方法”。它不像一个平方根函数或者类似的东西。
You just need to have a variable for the sum and loop through the array adding each value you find to the sum.
你只需要有一个变量来求和,并在数组中循环,将你找到的每个值相加。
#21
0
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
#22
0
As of Java 8 The use of lambda expressions have become available.
在Java 8中,lambda表达式的使用变得可用。
See this:
看到这个:
int[] nums = /** Your Array **/;
Compact:
简洁:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
喜欢:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.
返回或打印。
#23
-1
public class AddDemo {
public static void main(String[] args) {
ArrayList <Integer>A = new ArrayList<Integer>();
Scanner S = new Scanner(System.in);
System.out.println("Enter the Numbers: ");
for(int i=0; i<5; i++){
A.add(S.nextInt());
}
System.out.println("You have entered: "+A);
int Sum = 0;
for(int i=0; i<A.size(); i++){
Sum = Sum + A.get(i);
}
System.out.println("The Sum of Entered List is: "+Sum);
}
}