【问题标题】:Use a Variable Argument to find the Product of Numbers without ArrayList?使用变量参数来查找没有 ArrayList 的数字的乘积?
【发布时间】:2017-02-17 06:46:15
【问题描述】:

我正在练习使用可变参数,我希望能够找到数字的乘积。这是我可以弄清楚如何做到这一点的第一种方法。我觉得我可以不使用 ArrayList 来做到这一点,但我就是不知道怎么做。

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

【问题讨论】:

    标签: java arraylist variadic-functions


    【解决方案1】:

    您当然不需要那里的列表。只需遍历数组并制作产品。

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

    【讨论】:

    • 我可能会从 result == 1 开始
    • @Dirk 谢谢你的救命稻草:D
    • 哇。为什么我看不到这么简单的答案?太感谢了!我喜欢这种简单性。
    【解决方案2】:

    是的,您可以,变量参数被视为数组,请参阅answer,因此您可以像普通数组一样迭代它们:

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

    【讨论】:

    • 啊,这很有帮助!除了我会写“product *= num[i]”而不是“product *= num[1]”
    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2020-08-11
    • 1970-01-01
    相关资源
    最近更新 更多