• 當前位置:首頁 > IT技術 > 編程語言 > 正文

    java方法
    2022-05-11 11:08:56

    public class Demo02 {
        public static void main(String[] args) {
            int max = max(10,10);
            System.out.println(max);
    
        }
        //比大小
        public static int max(int num1,int num2){
            int result = 0;
            if(num1==num2){
                System.out.println("num1=num2");
                return 0;//終止方法
            }
            if(num1>num2){
                result = num1;
            }else{
                result = num2;
            }
            return  result;
    
        }
    }
    

    重載:在一個類中,有相同的函數名稱,但形參不同的函數

    方法的重載規則:
    方法名稱必須相同
    參數列表必須不同
    方法的返回類型可以相同也可以不同
    僅僅返回類型不同不足以成為方法的重載

    public class Demo02 {
        public static void main(String[] args) {
            double max = max(10,10,10);
            System.out.println(max);
    
        }
        //比大小
        public static int max(int num1,int num2,int num3){
            int result = 0;
            if(num1==num2){
                System.out.println("num1=num2");
                return 0;//終止方法
            }
            if(num1>num2){
                result = num1;
            }else{
                result = num2;
            }
            return  result;
    
        }
        public static int max(int num1,int num2){
            int result = 0;
            if(num1==num2){
                System.out.println("num1=num2");
                return 0;//終止方法
            }
            if(num1>num2){
                result = num1;
            }else{
                result = num2;
            }
            return  result;
    
        }
    
    
    }
    


    可變長參數(只能放在參數的最后一位)

    public class Demo04 {
        public static void main(String[] args) {
            Demo04 demo04 = new Demo04();
            demo04.test(1,2,3,4,5);
        }
        public void test(int...i){
            System.out.println(i[4]);
        }
    }
    


    遞歸
    n!

    public class Demo05 {
        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);
            }
        }
    
    }
    

    本文摘自 :https://www.cnblogs.com/

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码