可變參數java
解決參數個數不肯定引發的問題。數組
可變參數的本質是一個數組,編碼示例編碼
public class ChangedMethod { public static void main(String[] args) { double[] pay=new double[]{1,2,3}; double sunPay1=getSun1(pay); System.out.println("sunPay1:"+sunPay1); double sunPay2=getSun2(pay); System.out.println("sunPay2:"+sunPay2); double sunPay3=getSun3(pay); System.out.println("sunPay3:"+sunPay3); double sunPay4=getSun4(2,pay); System.out.println("sunPay4:"+sunPay4); } static double getSun1(double[] arr) { double sum=0.0; for(double price:arr){ sum += price; } return sum; } //可變參數 static double getSun2(double... arr) { double sum=0.0; for(double price:arr){ sum += price; } return sum; } static double getSun3(double[] arr) { double sum=0.0; for(int index = 0; index<arr.length; index++){ sum += arr[index]; } return sum; } //爲避免歧義,可變參數只能做爲最後一個參數 static double getSun4(double a,double... arr) { double sum=0.0; for(int index = 0; index<arr.length; index++){ sum += arr[index]; } return sum*a; } }
可變參數的本質是一個數組,編碼示例運行結果spa
sunPay1:6.0 sunPay2:6.0 sunPay3:6.0 sunPay4:12.0
可變參數必須做爲最後一個參數編碼示例code
public class ChangedMethod_02 { public static void main(String[] args) { double sun1=getSun1(1,2,3,4); System.out.println("sun1:"+sun1); double sun2=getSun2(1,2,3,4); System.out.println("sun2:"+sun2); double[] pay=new double[]{1,2,3,4}; double sunPay1=getSun1(pay); //不能用方法getSun2(double a, double... arr) System.out.println("sunPay1:"+sunPay1); } static double getSun1(double... arr) { double sum=0.0; for(double price:arr){ sum += price; } return sum; } static double getSun2(double a, double... arr) { double sum=0.0; for(double price:arr){ sum += price; } return sum*a; } }
可變參數必須做爲最後一個參數編碼示例程序運行結果get
sun1:10.0 sun2:9.0 sunPay1:10.0