java-学习8

  方法的声明及使用

public class function {
    public static void main(String[] args) {
        printInfo();//调用printInfo()方法
        printInfo();//调用printInfo()方法
        printInfo();//调用printInfo()方法
        System.out.println("hellow Worrld!");
        //此处由于此方法是由main方法直接调用的,所以一定要加上public static
                
}
    private static void printInfo() {
        // TODO Auto-generated method stub
        char c[]= {'h','e','l','l','o',',','L','X','H'};
        for(int x=0;x<c.length;x++) {
            System.out.println(c[x]);
        }
        System.out.println("");
    }
}

输出:

hello,LXH
hello,LXH
hello,LXH

hellow Worrld!

范例: 有返回值的方法

public class functin1 {
    public static void main(String[] args) {
        int one=addOne(10,20);//调用整数的加法操作
        float two=addTwo(10.3f,13.3f);//调用浮点数的加法操作
        System.out.println("One的计算结果"+one);
        System.out.println("Two的计算结果"+two);
    }
    //

    private static int addOne(int i, int j) {
        // TODO Auto-generated method stub
        int temp=0;
        temp=i+j;
        return temp;
    }

    private static float addTwo(float f, float g) {
        // TODO Auto-generated method stub
        float temp=0;
        temp=f+g;
        return temp;
    }
}

输出:

One的计算结果30
Two的计算结果23.6

  验证方法的重载

public class function2 {
    public static void main(String[] args) {
        int one=add(10,20);
        int two=add(10,20,30);
        float three=add(10.3f,13.3f);
        System.out.println("add(int i, int j)的计算结果:"+one);
        System.out.println("add(int i, int j,int k)的计算结果:"+two);
        System.out.println("add(float f, float g)的计算结果:"+three);
    }

    private static int add(int i, int j) {
        // TODO Auto-generated method stub
        int temp=0;
        temp=i+j;
        return temp;
    }

    private static int add(int i, int j, int k) {
        // TODO Auto-generated method stub
        int temp=0;
        temp=i+j+k;
        return temp;
    }

    private static float add(float f, float g) {
        // TODO Auto-generated method stub
        float temp =0;
        temp =f+g;
        return temp;
    }
    
}

输出:

add(int i, int j)的计算结果:30
add(int i, int j,int k)的计算结果:60
add(float f, float g)的计算结果:23.6
原文地址:https://www.cnblogs.com/liaohongwei/p/9890918.html