15、方法的定义和调用

方法的定义

image-20210623154427351

  • 形式参数:用来定义作用的
  • 实际参数:实际调用传递给它的参数

方法调用

image-20210623155645008

public class MethodDemo02 {
    public static void main(String[] args) {
        int max = max(1, 1);
        System.out.println(max);
    }

    //比大小
    public static int max(int a, int b) {
        int result = 0;

        if ( a == b ) {
            System.out.println(a + "和" + b + "相等");
            return 0;
        }

        if ( a > b ) {
            result = a;
        } else {
            result = b;
        }
        return result;
    }
}

当 a 为 1,b 为 1 时:

image-20210623160442840

当 a 为 2,b 为 1 时:

image-20210623160549023

使用三元运算符

public class MethodDemo03 {
    public static void main(String[] args) {
        int max = max(5, 2);
        System.out.println(max);
    }

    public static int max(int a,int b) {
        int result = 0;
        if ( a == b ) {
            System.out.println(a + "和" + b + "相等");
            return 0;
        }
        result = a > b ? a : b;
        return result;
    }
}

当 a 为 5,b 为 2 时:

image-20210623161053707

当 a,b 都为 2 时:

image-20210623161130173

扩展

public class MethodDemo04 {
    public static void main(String[] args) {
        int max = max();
        System.out.println("最大的数为:" + max);
    }

    public static int max() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入两个数:");
        int a = sc.nextInt();
        int b = sc.nextInt();

        int result = 0;
        if ( a == b ) {
            System.out.println(a + "和" + b + "相等");
            return 0;
        }

        if ( a > b ) {
            result = a;
        } else {
            result = b;
        }

        return result;
    }
}

image-20210623161743919

image-20210623161804096

posted @ 2021-06-26 17:08  多瑞C  阅读(58)  评论(0)    收藏  举报