17、可變引數
阿新 • • 發佈:2021-06-26
可變引數
實際上引數是陣列
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); } }
當沒有傳遞引數時:
傳遞引數時: