Java方法详解

时间:2021-08-30 14:20:12   收藏:0   阅读:20

什么是方法

package com.bing.method;

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(){
        for (int i = 0; i <= 1000; i++) {
            if(i%5==0){
                System.out.print(i+"\t");
            }
            if(i%(5*3)==0){ //换行
                //???每过3个就是15的倍数,能整除15就满足条件???
                System.out.println();
                // System.out.print("\n");
            }
        }
    }
}

方法的定义

? Java方法类似于其他语言的函数,是一段用来完成特定功能的代码片段,一般情况下,定义一个方法包含以下语法:

修饰符 返回值类型 方法名 (参数类型 参数名){
    ...
    方法体
    ...
    return 返回值;
}

Demo02

package com.bing.method;

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 CommandLine{
    public static void main(String[] args){
        for(int i = 0;i<args.length; i++){
            System.out.println("args[" + i + "]:" + args[i]);
        }
    }
}

可变参数

package com.bing.method;

public class Demo04 {
    public static void main(String[] args) {
        //调用可变参数的方法
        printMax(34,3,3,2,56.5);
        printMax(new double[]{1,2,3});

    }

    public static void printMax(double... numbers){
        if(numbers.length == 0){
            System.out.println("No argument passed");
            return;
        }

        double result = numbers[0];

        //排序
        for(int i =1;i < numbers.length; i++){
            if(numbers[i] > result){
                result = numbers[i];
            }
        }
        System.out.println("The max value is" + result);
    }

}

?递归?

package com.bing.method;

public class Demo06 {

    //2!  2*1
    //5!  5*4*3*2*1

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

    public static int f(int n){

        if(n==1){
            return 1;
        }else{
            return  n*f(n-1);
        }
    }

}

原文:https://www.cnblogs.com/ZzzZzzy-/p/15200636.html

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