十七、java中的方法

来源:互联网 发布:excel中vba编程 编辑:程序博客网 时间:2024/06/05 09:36

一、所谓方法,就是用来解决一类问题的代码的有序组合,是一个功能模块。

一般情况下,定义一个方法的语法是:
**访问修饰符 返回值类型 方法名(参数列表 ){
方法体
}**
其中:

1、 访问修饰符:方法允许被访问的权限范围, 可以是 public、protected、private 甚至可以省略 ,其中 public 表示该方法可以被其他任何代码调用,其他几种修饰符的使用在后面章节中会详细讲解滴

2、 返回值类型:方法返回值的类型,如果方法不返回任何值,则返回值类型指定为 void ;如果方法具有返回值,则需要指定返回值的类型,并且在方法体中使用 return 语句返回值

3、 方法名:定义的方法的名字,必须使用合法的标识符

4、 参数列表:传递给方法的参数列表,参数可以有多个,多个参数间以逗号隔开,每个参数由参数类型和参数名组成,以空格隔开

根据方法是否带参、是否带返回值,可将方法分为四类:

Ø 无参无返回值方法

Ø 无参带返回值方法

Ø 带参无返回值方法

Ø 带参带返回值方法

public class HelloWorld {    //定义了一个方法名为 print 的方法,实现输出信息功能    public void print() {        System.out.println("Hello World");    }    public static void main(String[] args){        //在 main 方法中调用 print 方法        HelloWorld test=new HelloWorld();        test.print();    }}

二、无参无返回值方法的使用
public void showMyLove(){}
三、无参带返回值

public class show {     public static void main(String[] args) {            // 创建对象,对象名为hello            show hello=new show();           // int sum=hello.calcSum();            System.out.println("两数之和为:"+hello.calcSum());        }        public int calcSum() {            int a=5;            int b=4;            int sum=a+b;            return sum;        }}

<1>如果方法的返回类型为 void ,则方法中不能使用 return 返回值!
public void shoeInfo(){
return “java”;
}
<2> 方法的返回值最多只能有一个,不能返回多个值
public int getInfo(){
int score1=12;
int score2=34;
return score1,score2;
}
<3>方法返回值的类型必须兼容,例如,如果返回值类型为 int ,则不能返回 String 型值
public int getInfo(){
String name=”hello”;
return name;
}

public class show {     public static void main(String[] args) {            // 创建对象,对象名为hello            show hello=new show();            double avg =hello.calcAvg();         System.out.println("平均成绩为:" + avg);        }        // 定义一个返回值为double类型的方法        public double calcAvg() {               double java = 92.5;            double php = 83.0;            double avg = (java + php) / 2; // 计算平均值                     // 使用return返回值            return avg;        }}

练习:

public class show {     public static void main(String[] args) {            // 创建对象,对象名为hello            show hello=new show();            int max=hello.maxAge();        System.out.println("最大年龄为:" + max);        }        // 定义一个返回值为double类型的方法        public int maxAge() {               int[] age={18 ,23 ,21 ,19 ,25 ,29 ,17};            int max=age[0];            for(int i=0;i<age.length;i++){                if(age[i]>max){                    max=age[i];                }            }                    // 使用return返回值            return max;        }}

运行结果:最大年龄为:29
四、Java 中带参无返回值方法的使用

public void show(String name){System.out.println("欢迎你"+name);}HelloWorld hello=new HelloWorld();hello.show("java");

<1>调用带参方法时,必须保证实参的数量、类型、顺序与形参一一对应
这里写图片描述
<2> 调用方法时,实参不需要指定数据类型,如

hello.show("java");

<3>方法的参数可以是基本数据类型,如 int、double 等,也可以是引用数据类型,如 String、数组等

import java.util.Arrays;public class HelloWorld{public static void main(String[] args){HelloWorld hello=new HelloWorld();int[] scores={1,2.3};hello.print(scores);}public void print(int[] scores){System.out.println(Arrays.toStrign(scores));}}

<4> 当方法参数有多个时,多个参数间以逗号分隔

public int clac(int num1,int num2){int num3=num1+num2;return num3;}
public class show {     public static void main(String[] args) {            // 创建对象,对象名为hello            show hello=new show();            // 调用方法,传入两门课程的成绩            hello.calcAvg(94, 81);        }        /*         * 功能:计算两门课程考试成绩的平均分并输出平均分         * 定义一个包含两个参数的方法,用来传入两门课程的成绩         */         public void calcAvg(int num1,int num2){             double avg=(num1+num2)/2.0;             System.out.println("平均分:"+avg);         }}

运行结果:平均分:87.5
五、Java 中带参带返回值方法的使用

public String show(Strign name){return "欢迎你"+name+"!";}

调用该方法:

HelloWorld hello=new HelloWorld();String welcome=hello.shoe("JAVA");System.out.println(welcome);

练习:

public class show {     public static void main(String[] args) {            // 创建对象,对象名为hello            show hello=new show();            int[] scores={79,52,98,81};            //调用方法,传入成绩数组,并获取成绩的个数            int count=hello.sort(scores);            System.out.println("共有"+count+"个成绩信息!");        }        /*         * 功能:将考试成绩排序并输出,返回成绩的个数         * 定义一个包含整型数组参数的方法,传入成绩数组         * 使用Arrays类对成绩数组进行排序并输出         * 方法执行后返回数组中元素的个数         */        public int sort(int[] scores){            Arrays.sort(scores);     System.out.println(Arrays.toString(scores));            //返回数组中元素的个数            return scores.length;        }

运行结果:
[52,79,81,98]
共有4个成绩信息!
六、方法的重载
如果同一个类中包含了两个或两个以上方法名相同、方法参数的个数、顺序或类型不同的方法,则称为方法的重载,也可称该方法被重载了。如下所示 4 个方法名称都为 show ,但方法的参数有所不同,因此都属于方法的重载:
这里写图片描述
如何区分调用的是哪个重载方法
当调用被重载的方法时, Java 会根据参数的个数和类型来判断应该调用哪个重载方法,参数完全匹配的方法将被执行。如:
这里写图片描述
判断方法重载的依据:

1、 必须是在同一个类中

2、 方法名相同

3、 方法参数的个数、顺序或类型不同

4、 与方法的修饰符或返回值没有关系
练习:

//导入java.util.Arrays;import java.util.Arrays;public class HelloWorld {    public static void main(String[] args) {         // 创建对象,对象名为hello        HelloWorld hello = new HelloWorld();        // 调用方法并将返回值保存在变量中        int[] nums = hello.getArray(8);        // 将数组转换为字符串并输出        System.out.println(Arrays.toString(nums));     }    /*     * 功能:创建指定长度的int型数组,并生成100以内随机数为数组中的每个元素赋值     * 定义一个带参带返回值的方法,通过参数传入数组的长度,返回赋值后的数组     */    public int[] getArray(int length) {        // 定义指定长度的整型数组        int[] nums = new int[length];        // 循环遍历数组赋值        for (int i=0;i<nums.length;i++) {            // 产生一个100以内的随机数,并赋值给数组的每个成员        nums[i]= (int)(Math.random() * 100);        }        return nums; // 返回赋值后的数组    }}

ps:Math.random() 生成 0–1 的浮点数。
七、编程练习
定义一个包含整型数组参数的方法,用来接收成绩数组,进行成绩排序并输出前三名


import java.util.Arrays;
public class show {
public static void main(String[] args) {
// 创建对象,对象名为hello
show hello=new show();
int[] scores={89 , -23 , 64 , 91 , 119 , 52 , 73};
hello.sort(scores);
}
//定义方法完成成绩排序并输出前三名的功能
public void sort(int[] scores){
Arrays.sort(scores);
int nums=0;//有效成绩的个数
System.out.println("考试成绩的前三名为");
for ( int i = scores.length - 1;i>= 0&&nums<3; i-- ) {
if(scores[i]<0||scores[i]>100){
continue;
}
nums++;
System.out.println(scores[i]);
}
}}
运行结果:
考试成绩的前三名为:
91
89
73

原创粉丝点击