Day05

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;
  }
}

 

方法的重载

  1. 方法名必须相同

  2. 参数列表必须不同(个数不同、或类型不同、或参数排列顺序不同等)

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);
      }
  }
}

 

posted @ 2021-03-09 17:24  Boom、  阅读(31)  评论(0)    收藏  举报