方法基础
**方法(method):**就是完成特定功能的代码块!
通过方法的定义和调用,可大大进步代码的复用性与可读性!
关于方法,我们实在并不生疏,从开始学Java到如今天天都会使用main方法,具体如下:
- public class 测试类名 {
- //main方法是一个特殊的方法,其是程序的入口
- public static void main(String[] args) {
- System.out.println("hello method");
- }
- }
复制代码 1 方法定义
在类中定义方法的固定格式如下:
- 修饰符 返回值类型 方法名(形式参数列表) {
- 方法体语句;
- }
复制代码 比方:
- public static int getSum(int a, int b) {
- int sum = a + b;
- return sum;
- }
复制代码 方法定义细节:
- 修饰符:当下固定为public static,后续再增补其他形式
- 返回值类型:根据该方法的具体功能而定
- 假如方法的作用仅做输出,不需要返回数据,则为 void
- 假如方法需要盘算一个结果并返回,则为结果类型,比如方法要求2个int数的和,则为 int
- 方法名
- 见名知意,方法名的形貌性要好
- 驼峰命名法,假如只有一个单词全小写
例:display() sum()
- 假如多个单词构成,则第一个单词全小写,后续单词首字母大写
例:sayHello() getMax() findStudentById()
- 形式参数列表
- 根据该方法的具体功能而定
- 具体案比方下
盘算2个int数的和,则 int getSum(int a, int b);
盘算3个int数的平均数,则 double getAvg(int x, int y, int z);
遍历一个数组,则 void outArray(int[] array);
- 方法体语句:方法的具体实现,要根据方法功能书写代码
案例:
- package com.briup.chap03;
- public class Test06_Function {
- // 获取两个int数较大值
- public static int getMax(int a, int b) {
- if(a > b)
- return a;
- return b;
- }
- // 求三个int数的平均值
- public static double getAvg(int x, int y, int z) {
- double sum = x + y + z;
- double avg = sum / 3;
- return avg;
- }
- }
复制代码 注意事项:
- 带参方法定义时,参数中的数据类型与变量名都不能缺少,缺少任意一个步伐将报错
- 带参方法定义时,多个参数之间使用逗号(,)分隔
2 方法调用
方法调用格式:
方法名(实际参数列表);
- //在上述Test06_Function类中添加测试方法
- public static void main(String[] args) {
- // 10,20是实际参数
- int max = getMax(10, 20);
- System.out.println("max: " + max);
- int x = 10;
- int y = 20;
- // a,b是实际参数
- max = getMax(x, y);
- System.out.println("max: " + max);
- // ...
- }
复制代码 注意事项:
- 方法必须先定义,再调用
- 实际参数列表可以是常量,也可以是变量,也可以是表达式
- 实际参数类型要匹配形式参数类型(要么完全雷同,要么能主动隐式类型转换)
- main方法是入口方法,一个步伐中唯一,其可以调用其他普通方法
- 其他方法不能调用main方法,普通方法可以相互调用
案例1:
设计一个方法用于判断一个整数是否为闰年。
- package com.briup.chap03;
- import java.util.Scanner;
- public class Test06_LeapYear {
- //判断是否为闰年
- //函数传参过程:main方法中函数调用 isLeapYear(y);
- // int year = y; 将y的值传递给year,让其参与运算
- public static boolean isLeapYear(int year) {
- if((year % 4 == 0 && year % 100 != 0)
- || year % 400 == 0)
- return true;
-
- return false;
- }
-
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个年份: ");
- int y = sc.nextInt();
-
- if(isLeapYear(y))
- System.out.println("闰年");
- else
- System.out.println("非闰年");
- }
- }
复制代码 案例2:
设计一个方法用于判断一个整数是否是水仙花数,在控制台输出所有的水仙花数。
- package com.briup.chap03;
- public class Test06_Flower {
- //判断一个整数是否是水仙花数
- public static boolean isFlower(int number) {
- int g = number % 10;
- int s = number / 10 % 10;
- int b = number / 100 % 10;
-
- if ((g*g*g + s*s*s + b*b*b) == number) {
- return true;
- } else {
- return false;
- }
- }
-
- public static void main(String[] args) {
- // 遍历所有的3位数,逐个判断是否是水仙花数
- for(int i = 100; i < 1000; i++) {
- boolean f = isFlower(i);
- if(f)
- System.out.println(i + " 是水仙花数!");
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |