Java method to sum any number of ints

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

    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);
        }
    
    }
    

提交回复
热议问题