gpt4 book ai didi

java - 关于变量参数和匿名数组

转载 作者:行者123 更新时间:2023-12-01 17:26:06 26 4
gpt4 key购买 nike

请告知如何将下面的程序转换为变量参数,这是java 5引入的新功能,现在我正在使用匿名内部数组..

public class AnnonymousArrayExample {

public static void main(String[] args) {

//calling method with anonymous array argument
System.out.println("first total of numbers: " + sum(new int[]{ 1, 2,3,4}));
System.out.println("second total of numbers: " + sum(new int[]{ 1, 2,3,4,5,6,}));

}

//method which takes an array as argument
public static int sum(int[] numbers){
int total = 0;
for(int i: numbers){
total = total + i;
}
return total;
}
}

最佳答案

使用变量参数

public static int sum(int... numbers){}
<小时/>

另请参阅

关于java - 关于变量参数和匿名数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14889482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com