1

I am practicing with variable arguments and I want to be able to find the product of numbers. This is the first way that I could figure out how to do it. I feel like I can do it without using an ArrayList, but I just can't see how.

import java.util.*;

public class variableMethod
{
    public static void main(String[] satharel)
    {
        System.out.printf("The product of 5 and 10: \t\t%3d%n", productFinder(5, 10));
        System.out.printf("The product of 2 and 3 and 4: \t\t%3d%n", productFinder(2, 3, 4));
        System.out.printf("The product of 1 and 2 and 3: \t\t%3d%n", productFinder(1, 2, 3));
        System.out.printf("The product of 7 and 2 and 4 and 5: \t%3d%n", productFinder(7, 2, 4, 5));

    }

    public static int productFinder(int... num)
    {
        ArrayList<Integer> numbers = new ArrayList<Integer>();

        for(int n : num)
            numbers.add(n);

        int first = numbers.get(0);

        for(int i = 1; i < numbers.size(); i++)
            first *= numbers.get(i);

        return first;
    }
}

2 Answers 2

3

Surely you dont need a list there. Just iterate over array and make product.

public static int productFinder(int... num) {
        int result = 1;
        for (int i = 0; i < num.length; i++) {
            result *= num[i];
        }
        return result;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I'd probably start with result == 1
@Dirk Thankyou life saver :D
Wow. Why could I not see such a simple answer? Thank you so much! I love the simplicity of this.
1

Yes you can, variable arguments are treated as arrays see this answer so you can iterate them like a normal array:

public static int productFinder(int... num)
{
    int product = 1;
    for(int i = 0; i < num.length; i++) {
        product *= num[i];
    }
    return product;
}

1 Comment

Ah, that's very helpful! Except I would write "product *= num[i]" instead of "product *= num[1]"

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.