Java 如何执行 int[] 数组的求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9813573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:00:50  来源:igfitidea点击:

How to perform a sum of an int[] array

javaarraysloops

提问by Jordan Westlund

Given an array Aof 10 ints, initialize a local variable called sumand use a loop to find the sum of all numbers in the array A.

给定一个A10的数组ints,初始化一个名为的局部变量sum并使用循环来查找数组中所有数字的总和A

This was my answer that I submitted:

这是我提交的答案:

sum = 0;
while( A, < 10) {
   sum = sum += A;
}

I didn't get any points on this question. What did I do wrong?

在这个问题上我没有得到任何分数。我做错了什么?

采纳答案by StriplingWarrior

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:

您的语法和逻辑在很多方面都不正确。您需要创建一个索引变量并使用它来访问数组的元素,如下所示:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) {   // The indexer needs to be less than 10, not A itself.
   sum += A[i];   // either sum = sum + ... or sum += ..., but not both
   i++;           // You need to increment the index at the end of the loop.
}

The above example uses a whileloop, since that's the approach you took. A more appropriate construct would be a forloop, as in Bogdan's answer.

上面的示例使用了一个while循环,因为这是您采用的方法。更合适的构造是for循环,如 Bogdan 的回答。

回答by Bogdan Emil Mariesan

int sum = 0;
for(int i = 0; i < A.length; i++){
  sum += A[i];
}

回答by Mark Rhodes

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the whileloop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:

当你声明一个变量时,你需要声明它的类型 - 在这种情况下:int. 此外,您在while循环中放置了一个随机逗号。可能值得查找 Java 的语法并考虑使用能够识别此类错误的 IDE。你可能想要这样的东西:

int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
    sum += numbers[i];
}
System.out.println("The sum is: " + sum);

回答by kasavbere

int sum=0;
for(int i:A)
  sum+=i;

回答by msayag

Once java-8is out (March 2014) you'll be able to use streams:

一旦java-8发布(2014 年 3 月),您将能够使用流:

int sum = IntStream.of(a).sum();

or even

甚至

int sum = IntStream.of(a).parallel().sum();

回答by ella2469

Here is an efficient way to solve this question using For loops in Java

这是在 Java 中使用 For 循环解决此问题的有效方法

 public static void main(String[] args) {

    int [] numbers = { 1, 2, 3, 4 };
    int size = numbers.length;

    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    System.out.println(sum);
}