Java method to sum any number of ints

后端 未结 7 758
不思量自难忘°
不思量自难忘° 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:06

    If your using Java8 you can use the 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());
    

    Results: 181

    Just 1 line of code which will sum the array.

提交回复
热议问题