循环使用不同参数的方法调用

时间:2013-11-18 18:05:12

标签: java

似乎应该有一种方法用for()循环编写product()调用。我无法弄清楚该怎么做。有人知道吗?

// 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 [0])到产品(i [0],i [1],i [2] ......,[9])的参数调用产品

最终代码:

// 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

3 个答案:

答案 0 :(得分:2)

您需要使用所需数量的项创建int的临时数组,将i的子数组复制到该临时数组中,然后将其传递给product像这样:

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));
}

答案 1 :(得分:0)

我循环并跟踪每个产品结果,然后将这些值放在一个新数组中。最后,使用所有产品在新创建的阵列上调用product方法。

int[] listOfProducts = new int[i.length];
int [] tempArray;
for(int x = 0; x<i.length; x++){
    //copy i[0] to i[x] into tempArray
    System.arraycopy(i, 0, tempArray, 0, x+1);
    listOfProducts[x] = product(tempArray);
}
System.out.println(product(listOfProducts));

答案 2 :(得分:0)

如果我理解正确,你正在寻找一种方法来编写一个带有可变数量参数的product方法。这可以通过使用...语法来实现,这将使您的方法获取给定类型的任意数量的参数,并允许您将它们作为方法内的数组来处理。 E.g:

public static int product (int... numbers) {
    int product = 1;
    for (int number : numbers) {
        product *= number;
    }
    return product;
}
相关问题