9

我需要编写一个 java 方法sumAll(),它接受任意数量的整数并返回它们的总和。

sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20

我不知道该怎么做。

4

7 回答 7

20

如果您使用 Java8,则可以使用IntStream

int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());

结果:181

只需 1 行代码即可对数组求和。

于 2014-05-19T22:16:50.067 回答
14

你需要:

public int sumAll(int...numbers){

    int result = 0;
    for(int i = 0 ; i < numbers.length; i++) {
        result += numbers[i];
    } 
    return result;
}

然后调用该方法并根据需要为其提供尽可能多的 int 值:

int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
于 2013-06-16T05:42:41.350 回答
9
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 
于 2013-06-16T05:43:39.937 回答
2

使用var 参数

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}
于 2013-06-16T05:40:11.237 回答
1
import java.util.Scanner;

public class SumAll {
    public static void sumAll(int arr[]) {//initialize method return sum
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.println("Sum is : " + sum);
    }

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);//create scanner object 
        System.out.print("How many # you want to add : ");
        num = input.nextInt();//return num from keyboard
        int[] arr2 = new int[num];
        for (int i = 0; i < arr2.length; i++) {
            System.out.print("Enter Num" + (i + 1) + ": ");
            arr2[i] = input.nextInt();
        }
        sumAll(arr2);
    }

}
于 2014-08-30T11:52:25.220 回答
0
 public static void main(String args[])
 {
 System.out.println(SumofAll(12,13,14,15));//Insert your number here.
   {
      public static int SumofAll(int...sum)//Call this method in main method.
          int total=0;//Declare a variable which will hold the total value.
            for(int x:sum)
          {
           total+=sum;
           }
  return total;//And return the total variable.
    }
 }
于 2014-02-05T10:55:03.583 回答
0

你可以这样做,假设你有一个具有值和数组长度的数组:arrayVal[i]arrayLength

int sum = 0;
for (int i = 0; i < arrayLength; i++) {
    sum += arrayVal[i];
}

System.out.println("the sum is" + sum);

我希望这有帮助。

于 2014-05-03T11:36:12.147 回答