public static void main(String[] args){ int max = max(10,21); //double max = max(10,20); variable max is already defined in the scope //一个作用域不能定义多个相同变量名的变量 double max2 = max(10,20); System.out.println(max); } public static double max(double num1,double num2){ double res = 0; if(num1==num2){ System.out.println(num1+"="+num2); return 0;//终止max方法 } if(num1>num2) res = num1; else res = num2; return res; } public static int max(int num1,int num2){//方法重载,方法名相同,参数类型不同 int res = 0; if(num1==num2){ System.out.println(num1+"="+num2); return 0;//终止max方法 } if(num1>num2) res = num1; else res = num2; return res; }
在方法声明中,指定参数类型后加一个省略号(...),任何普通的参数都要在前面声明
public static void main(String[] args) { getMax(1,2,3,4); getMax(new double[]{1,2,3,4,5});//本质是一个数组 } public static double getMax(double... numbers) { if (numbers.length == 0) return 0; double max = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i] > max) max = numbers[i]; } System.out.println("max=" + max); return max; }