可变参数
实际上参数是数组
public class MethodDemo07 {
public static void main(String[] args) {
MethodDemo07 demo07 = new MethodDemo07();
demo07.test(1,2,3,4,5,6,7,8,9);
}
public void test(int... numbers) {
for ( int i = 0; i < numbers.length; i++ ) {
System.out.println("第" + (i+1) + "个值为:" + numbers[i]);
}
}
}
public class MethodDemo08 {
public static void main(String[] args) {
MethodDemo08 demo08 = new MethodDemo08();
demo08.printMax();
//demo08.printMax(2.5,3.5,1.2,8.9,4.2);
}
public void printMax(double... numbers) {
if ( numbers.length == 0 ) {
System.out.println("未传递任何参数");
return; //结束标志
}
double results = numbers[0];
//排序
for ( int i = 0; i < numbers.length; i++ ) {
if ( numbers[i] > results ) {
results = numbers[i];
}
}
System.out.println("最大的数为:" + results);
}
}
当没有传递参数时:
传递参数时: