Java method to sum any number of ints

后端 未结 7 711
不思量自难忘°
不思量自难忘° 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);
        }
    
    }
    
    0 讨论(0)
  • 2021-01-02 08:51

    Use var args

    public long sum(int... numbers){
          if(numbers == null){ return 0L;}
          long result = 0L;
          for(int number: numbers){
             result += number;
          }
          return result;   
    }
    
    0 讨论(0)
  • 2021-01-02 08:58
    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
    } 
    
    0 讨论(0)
  • 2021-01-02 09:01
     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.
        }
     }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题