java java可选参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1737350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java optional parameters
提问by Hellnar
I want to write an average method in java such that it can consume N amount of items, returning the average of them:
我想在java中编写一个平均方法,以便它可以消耗N个项目,返回它们的平均值:
My idea was:
我的想法是:
public static int average(int[] args){
int total = 0;
for(int i=0;i<args.length;i++){
total = total + args[i];
}
return Math.round (total/args.length);
}
//test it
average(1,2,3) // s**hould return 2.
how can I change my method to consume any amount of parameters instead of int[] args so can work the way I want ? Cheers
如何更改我的方法以使用任意数量的参数而不是 int[] args 以便可以按我想要的方式工作?干杯
回答by Brian Agnew
回答by coobird
Since Java 5, there is a feature commonly called varargswhich achieves what is desired.
从 Java 5 开始,有一个通常称为varargs的功能可以实现所需的功能。
Here's a little example:
这是一个小例子:
public static int add(int... nums) {
int total = 0;
for (int n : nums)
total += n;
return total;
}
public static void main(String[] s) {
// The following prints "10"
System.out.println(add(1, 2, 3, 4));
}
回答by user140301
function average() {
函数平均(){
var total = 0;
if(arguments.length > 0) {
for(var i = 0, n = arguments.length; i < n; i++) {
total += parseFloat(arguments[i]);
}
total /= arguments.length;
}
return total;
}
}
回答by Dafydd Rees
Here's the optional arguments version (almost no code changes...)
这是可选参数版本(几乎没有代码更改......)
public class Spike2 {
public static final void main(String argv[]) {
System.out.println(average(1,2,3));
}
public static int average(int... args){
int total = 0;
for(int i=0;i<args.length;i++){
total = total + args[i];
}
return Math.round (total/args.length);
}
}
with iterator changes:
随着迭代器的变化:
public class Spike2 {
public static final void main(String argv[]) {
System.out.println(average(1,2,3));
}
public static int average(int... args){
int total = 0;
for(int i: args){
total = total + i;
}
return Math.round (total/args.length);
}
}

