2

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

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

this works perfectly, i have never seen Integer... used before. Does the three dots represent an array of integers?
You can also use the primitive type int instead of Integer. Yes, it basically means that you can add as many integer parameters as you want and it will the build an array out of it. Can be very handy sometimes :)
Yes that is a real handy tool, never seen it being used in any text. Great Stuff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.