Day05
方法
在main方法外定义,main方法中调用
一个方法只实现一个功能
修饰符 返回值类型 方法名 (参数类型 参数名){
...
方法体
...
return 返回值;
}
调用方法:对象名.方法名(实参列表)
如果方法返回值是void,方法调用一定是一条语句。
Java(值传递)
public class Demo01 {
public static void main(String[] args) {
int max = max(20,20);
System.out.println(max);
}
//比大小
public static int max(int num1,int num2){
int result;
if(num1==num2){
System.out.println("num1==num2");
return 0; //终止方法
}
if(num1>num2){
result = num1;
}
else {
result = num2;
}
return result;
}
}
方法的重载
-
方法名必须相同
-
参数列表必须不同(个数不同、或类型不同、或参数排列顺序不同等)
public class Demo03 {
public static void main(String[] args) {
test(56,454,465,45,4,5,2);
}
public static void test(double... number){
if (number.length==0){
System.out.println("miss");
}
double result=number[0];
for (int i=0;i< number.length;i++){
if (number[i]>result) {
result = number[i];
}
}
System.out.println(result);
}
}
(阶乘)
public class Demo04 {
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int n){
if (n == 1){
return 1;
}
else{
return n*f(n-1);
}
}
}

浙公网安备 33010602011771号