Java方法

2021/6/13 20:21:28

本文主要是介绍Java方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java方法

方法的定义

package com.zhang.method;

public class Demo01 {
    public static void main(String[] args) {
        int sum = add(1,2);
        System.out.println(sum);
        num(2,50);
    }
    // 加法
    public static int add(int a,int b){
        return a+b;
    }
    //打印5的倍数
    public  static void num(int a,int b){
        for(int i=a;i<=b;i++){
            if(i%5==0)
                System.out.print(i+"\t");
            if((i%(5*3))==0)
                System.out.println();
        }
    }
}

方法调用

package com.zhang.method;

public class Demo02 {
    public static void main(String[] args) {
        double result=max(15,15.5);
        System.out.println(result);
    }
    //比大小                   形参
    public static double max(double a,double b){
        double  result=0;
        result=a>b?a:b;
        if(a==b)
            result = a;
        return result;
    }
}

方法的重载

就是同名 不同形参的方法。

package com.zhang.method;

public class Demo03 {
    public static void main(String[] args) {
        double sum = add(5.5,6.4);
        System.out.println(sum);
    }
    public static int add(int a,int b) {
        return a + b;
    }
    //方法的重载             形参个数不同
    public static int add(int a,int b,int c) {
        return a + b + c;
    }
    //方法的重载             形参类型不同
    public static double add(double a,double b) {
        return a + b;
    }
}

命令行传参

package com.zhang.method;

public class Demo04 {
    public static void main(String[] args) {
        for (int i =0;i< args.length;i++){
            System.out.println(args[i]);
        }
    }
}

命令行执行要找到包的位置

可变参数

不定向参数

package com.zhang.method;

public class Demo05 {
    public static void main(String[] args) {
        Demo05 d5 = new Demo05();
        d5.test(1,3,4,5);
    }
    public void test (int ... i){ //可变长数组
        System.out.println(i[2]);
    }
}
package com.zhang.method;

public class Demo06 {
    public static void main(String[] args) {
        Demo06 d6 = new Demo06();
        double m1 = d6.max(1,25,56,85.4,2.3);
        double m2 = d6.max(50,20,1.5,3.2,12.3655,54.1);
        System.out.println(m1);
        System.out.println(m2);
    }
    public double max(double ... i){ //可变长数组,必须写在形参的最后
        double result=0;
        if (i.length==0){
            System.out.println("输入错误!");
            return 0;
        }
        result=i[0];
        for (int a=1;a<i.length;a++){
            if (i[a]>result)
                result = i[a];
        }
        return result;
    }
}

递归

package com.zhang.method;

public class Demo08 {
    public static void main(String[] args) {
        System.out.println(fun(3));
    }
    public static int fun(int n){
        if (n==1) {
            return 1;
        }else {
            return n*fun(n-1);
        }
    }
}



这篇关于Java方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程