1.函数的概念
- 实现特定功能的一段代码,可以反复使用。
- 函数的设计:遵循单一职能原则,一个函数只做一件事。
2.函数的定义
public static void 函数名称 () {
// 函数主体
}
- 一个类中可以定义多个函数,函数之间是并列关系,不可嵌套。
3.函数的调用
函数名();
4.函数的参数
// 函数主体
}
调用语法:
函数名(实际参数); // 实参 等价于 局部变量的赋值操作
如何定义参数?经验:根据具体的业务需求,来定义函数的参数。
【注意】字符串比较的问题:
== 默认比较的地址值,不是字符串内容
str1.equals(str2); 含义:比较s1中存储的字符串是否与s2相同, true相同
!str1.equals(str2); 含义:比较s1中存储的字符串是否与s2不同, true不同
5.函数的返回值
1)定义返回值类型:基本数据类型、引用数据类型、void
2)return value; // 函数可以返回一个结果,类型必须与函数定义的返回值一致
3)一个函数只能有一个返回值,如果函数中包含分支条件,需要保证所有的分支都有返回值
4)return 的两种用法:
A) return value; // 表示结束当前函数,并伴有返回值,返回到函数的调用处
B) return; // 表示结束当前函数,直接会返回到函数调用处
6.多级调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class TestGetSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println(sum);
int result = getSum (5);
System.out.println(result);
}
public static int getSum (int n) {
if (n == 1) {
return 1;
} else {
return n + getSum(n-1);
}
}
}
|

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public class TestFibonacci {
public static void main(String[] args) {
int result = fibonacci(7);
System.out.println(result);
}
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1){
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
}
|

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class Test06 {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
int unit = i % 10;
int decade = i / 10 % 10;
int hundred = i / 100;
if (getFact(unit) + getFact(decade) + getFact(hundred) == i) {
System.out.println("每位数字的阶乘之和等于其本身的3位数:" + i);
}
}
}
public static int getFact (int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return n * getFact(n-1);
}
}
}
|
