Day03 JAVA学习笔记之方法

Day03 JAVA学习笔记之方法,第1张

Day03 JAVA学习笔记之方法

简单的方法返回
public class Demo01 {
    //main方法
    public static void main(String[] args) {
        int sum = add(1,2);
        System.out.println(sum);

        test();
    }

    //加法方法
    public static int add(int a,int b){
        return a+b;
    }

    public static void test(){
        int[] numbers = {10,20,30,40,50};
        for(int x:numbers){
            System.out.println(x);
        }
    }
}
方法的定义 

 方法内的参数为形参,main方法内调用方法用的为实参。

方法调用

 

如果有返回值一定要有return;return是方法终止符

方法的重载 

 

 可变参数

 

public class Demo02 {
    public static void main(String[] args) {
        //调用可变参数的方法
        pirntMax(34,4,5,6);
        pirntMax((new double[]{1,3,5}));
    }

    private static void pirntMax(double... numbers){
        if(numbers.length == 0){
            System.out.println("no argument passed");
            return;
        }

        double result = numbers[0];

        //排序!
        for(int i = 1; i result){
                numbers[i] = result;
            }
        }
    }
}
递归

 

 

public class Demo03 {
    public static void main(String[] args) {
        System.out.println(f(5));
    }

    //5! 5*4*3*2*1
    public static int f(int n){
        if(n==1){
            return 1;
        }else {
            return n*f(n-1);
        }
    }
}

能不用递归就不用递归,java是栈机制。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5710333.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存