adding an unknown number of numbers in java

2.5k views Asked by At

I have the following code below:

public class Classes {

    /**
     * @param args the command line arguments
     */
public static void main(String[] args) {
int sum = add(10,20);

System.out.println(sum);


// TODO code application logic here
    }


public static int add(int number,int number2){
int c = number + number2;
return c;
}

} 

In this case i am adding 2 numbers together and returning them to my main method. I now want to alter this, but keeping to the same structure, a way of adding an unspecified number of numbers. For example if i wanted to add three numbers i would adjust the following to

public static int add(int number,int number2,int number3){
int c = number + number2 + number3;

I cant keep adding int numberx to public static int add(

so what do i do?

1

There are 1 answers

3
flogy On BEST ANSWER

You can submit an array of integers and then loop and summarize them.

public static int add(Integer... numbers) {
    int result = 0;
    for (Integer number : numbers) {
        result += number;
    }
    return result;
}