java方法:方法介绍、方法的重载、可变参数以及递归

时间:2021-09-05 17:09:26   收藏:0   阅读:50

java方法

概念

什么是方法

方法的定义

修饰符 返回值类型 方法名(参数类型 参数名){
    //方法体
    return 返回值;
}
package com.ljh.method;
public class Demo1 {
    public static void main(String[] args) {
        int compare = compare(5, 5);
        System.out.println(compare);
    }
    public static int compare(int a,int b){
        if (a==b){
            System.out.println("两个值相等");
            return 0;
        }
        if (a>b){
            return a;
        }else {
            return b;
        }
    }
}

方法的重载

package com.ljh.method;

/**
 * 方法的重载
 */
public class Demo2 {
    public static void main(String[] args) {
        
    }
    public static int add(int a,int b){
        return a+b;
    }
    public static double add(int a,int b,int c){
        return a+b+c;
    }
}

方法名相同,参数列表不同,与返回值类型无关

命令行传参

  1. 打开命令行进入该文件目录下javac进行编译该.java文件生成.class文件

    D:\ideaWorkSpace\javaSE\基础\基础语法\src\com\ljh\method>javac Demo3.java
    
  2. 进入src目录下(包名前,如果在class文件下,会找不到包路径) 输入java 包名.文件名称 参数...

    D:\ideaWorkSpace\javaSE\基础\基础语法\src>java com.ljh.method.Demo3 a b c
    

    输出的结果:

    a
    b
    c
    

可变参数

本质还是数组

package com.ljh.method;

/**
 * 可变参数
 */
public class Demo4 {
    public static void main(String[] args) {
        compare();
        compare(1,6,55,2,5);
        compare(new int[]{1,2,3,4,8});
    }
    public static void compare(int ... a){

        if(a.length==0){
            System.out.println("没有传递值");
            return;//跳出方法
        }
        int result=a[0];
        for (int x=1;x<a.length;x++){
            if (a[x]>result){
                result=a[x];
            }
        }
        System.out.println(result);

    }
}

递归

package com.ljh.method;

/**
 * 递归
 */
public class Demo5 {
    public static void main(String[] args) {
        System.out.println(f(5));
    }
    /*
    阶乘:1!=1
          2!=2*1
          3!=3*2*1
          n!=n*(n-1).....
    */
    public static int f(int i){
        if (i==1){//递归头
            return 1;
        }else {//递归体
            return i*f(i-1);
        }
    }
}

原文:https://www.cnblogs.com/ljhStudy/p/15226876.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!