0
点赞
收藏
分享

微信扫一扫

可变参数(不定项参数)

荷一居茶生活 2022-02-16 阅读 51
java
  • JDK1.5开始,Java支持传递同类型的可变参数给一个方法。

  • 在方法声明中,在指定参数类型后加一个省略号(...)。
  • 一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明。
package chap3_方法;

/**
* 可变参数(不定项参数)
*/


public class Test03 {
public static void main(String[] args) {
Test03 test03 = new Test03();
test03.test(1,2,3);

}
public void test(int... i){
System.out.println(i[0]); // 1
System.out.println(i[1]); // 2
System.out.println(i[2]); //3
}
}


package chap3_方法;

/**
* 可变参数(排序)
*/


public class Test04 {
public static void main(String[] args) {
prinMax(3,0,3);//3.0
prinMax(9.2,8);//9.2
}
public static void prinMax(double... numbers){
if (numbers.length == 0){
System.out.println("没有传递任何参数!");
return;
}
double result = numbers[0];
//排序
for (int i=1; i < numbers.length;i++){
if (numbers[i] > result){
result = numbers[i];
}
}
System.out.println("The max value is:" + result);
}
}
举报

相关推荐

0 条评论