1.概念
将一个功能抽取出来,放在类中的大括号中,形成一个独立的功能,当需要使用该功能时,则调用它,这样可以增强代码的复用性(重复利用),并解决代码的冗余现象。
2.结构
3.语法
public static int add(int a, int b) {
int d = a + b;
return d;
}
1.public:访问控制符
2.static:静态
3.int:方法的返回类型
4.add:方法名称
5.int a,int b:参数列表
6.{ }:作用域
3.1常见语法错误
1.方法中不能嵌套其他方法,但是可以调用其他方法
2.方法设计中有返回类型,方法体中没有返回
3.作用域-大括号
4.方法的形参和实参
5.方法重载
6.不定重载
不定重载,可以选择任意个数字相加
当大量重载方法时,影响程序的使用。不定参数本质时传入数组,但允许调用者随意传入参数个数,使用比较灵活。
6.方法递归
6.1递归的执行流程
1.找出递归的终止条件
2.找出解决问题的通项公式
6.2递归案例
/**
* 递归,解决阶层问题
* @param n
* @return
*/
public static int f (int n) {
if(n==1) return 1;
return n*f(n-1); //通项公式
}
/**
* 计算前n项之和
* @param n
* @return
*/
public static int sum(int n) {
if(n==1){
return 1;
}
return sum(n-1)+n;
}
7.方法常见案例
package com.zr.methods;
import java.util.Scanner;
public class Practise {
static final String USERNAME = "admin";
static final String PASSWORD = "123";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
/**
* 测试是否是闰年
*/
if (isLeap(2021)) {
System.out.println("是闰年");
} else {
System.out.println("是平年");
}
/**
* 测试是否是素数
*/
if (isPrimer(213123)) {
System.out.println("不是素数");
} else {
System.out.println("是素数");
}
/**
* 画等腰三角形
*/
drawPic01(5);
/**
* 测试找第二大数
*/
System.out.println(findSecond(3, 5, 12));
/**
* 测试登录
*/
if (login("username", "password")) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
f(7);
System.out.println(f2(5));
}
/**
* 判断是否为闰年
*
* @param year
*/
public static boolean isLeap(int year) {
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
return true;
}
return false;
}
/**
* 判断是否为素数
*
* @param n
* @return
*/
public static boolean isPrimer(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return true;
}
}
return false;
}
/**
* 画一个等腰三角形
*
* @param n 高度
*/
public static void drawPic01(int n) {
for (int j = 1; j <= n; j++) {
for (int b = 1; b <= n - j; b++) {
System.out.print(" ");
}
for (int i = 1; i <= 2 * j - 1; i++) {
System.out.print(".");
}
System.out.println();
}
}
/**
* 找出第二大数
*
* @param a
* @param b
* @param c
*/
public static int findSecond(int a, int b, int c) {
if (a > b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
if (c > b) {
return b;
} else if (c < a) { // 不能重复打印
return a;
} else {
return c;
}
}
/**
* 判断用户名密码是否正确
*
* @return
*/
public static boolean login(String username, String password) {
// 不能再次输入
if (username.equals(USERNAME) && password.equals(PASSWORD)) {
return true;
} else {
return false;
}
}
/**
* 1 1/2 2/3 3/5 5/8
*/
public static void f(int n) {
int a = 1;
int b = 1;
for (int i = 1; i <= n; i++) {
System.out.println(a + "/" + b);
int c = a + b;
a = b;
b = c;
}
}
/**
* 计算一下5!+4!+3!+2!+1!
*/
public static int f2(int n) {
int s = 1;
int sum = 0;
for (int i = 1; i <= n; i++) {
s *= i;
sum += s;
}
return sum;
}
}