我正在练习可变参数,我希望能够找到数字的乘积。这是我能弄清楚如何去做的第一种方法。我觉得我可以在不使用 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;
}
}
最佳答案
当然你不需要列表。只需遍历数组并生成产品。
public static int productFinder(int... num) {
int result = 1;
for (int i = 0; i < num.length; i++) {
result *= num[i];
}
return result;
}
关于java - 使用变量参数在没有 ArrayList 的情况下查找数字的乘积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291127/