Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through method calls with varying parameters

Tags:

java

It seems that there should be a way to write the product() calls with a for() loop. I cannot figure out how to do it. Does anybody know of a way?

// store numbers
int[] i = { 1, 7, 2, 4, 6, 54, 25, 23, 10, 65 };

System.out.println(product(i[0]));
System.out.println(product(i[0], i[1]));
........
System.out.println(product(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]));

public static int product(int... num) {...}

I already have product written, I just need to call product with arguments from product(i[0]) to product(i[0], i[1], i[2]..., [9]).

Final code:

// Calculate product of any amount of numbers
public static void main(String[] args)
{
    // create Scanner for input
    Scanner in = new Scanner(System.in);

    // store numbers
    int[] array = { 1, 7, 2, 4, 6, 14, 25, 23, 10, 35 };

    for (int j = 1 ; j <= array.length; j++) {

        // Construct a temporary array with the required subset of items
        int[] tmp = new int[j];

        // Copy from the original into the temporary
        System.arraycopy(array, 0, tmp, 0, j);

        // Make a call of product()
        System.out.println(product(tmp));

    }   // end for
}   // end method main

public static int product(int... num)
{
    // product
    int product = 1;

    // calculate product
    for(int i : num)
        product *= i;

    return product;

}   // end method product

1 Answers

You need to create a temporary array of ints with the required number of items, copy the sub-array of i into that temporary array, and then pass it to product like this:

for (int count = 1 ; count <= i.length() ; count++) {
    // Construct a temporary array with the required subset of items
    int[] tmp = new int[count];
    // Copy from the original into the temporary
    System.arraycopy(i, 0, tmp, 0, count);
    // Make a call of product()
    System.out.println(product(tmp));
}
like image 74
Sergey Kalinichenko Avatar answered Apr 18 '26 08:04

Sergey Kalinichenko