Java method to sum any number of ints

后端 未结 7 742
不思量自难忘°
不思量自难忘° 2021-01-02 08:25

I need to write a java method sumAll() which takes any number of integers and returns their sum.

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


        
7条回答
  •  既然无缘
    2021-01-02 09:09

    You need:

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

    Then call the method and give it as many int values as you need:

    int result = sumAll(1,4,6,3,5,393,4,5);//.....
    System.out.println(result);
    

提交回复
热议问题