1. 方法的基本用法
1.1 什么是方法
方法就是一个代码片段, 类似于 C 语言中的 “函数”,方法有一下几点意义:
- 能够模块化组织代码
- 做到代码被重复使用, 一份代码可以在多个位置使用.
- 让代码更好理解更简单.
- 直接调用现有方法开发, 不必重复编写
1.2 方法定义语法
- 基本语法格式:
// 方法定义
public static 方法返回值 方法名称([参数类型 形参 ...]){
方法体代码;
[return 返回值];
}
// 方法调用
返回值变量 = 方法名称(实参...);
- 代码示例:
- 实现一个方法实现两个整数相加
class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
// 方法的调用
int ret = add(a, b);
System.out.println("ret = " + ret);
}
// 方法的定义
public static int add(int x, int y) {
return x + y;
}
}
// 执行结果
ret = 30
- 计算 1! + 2! + 3! + 4! + 5!
class Test {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += factor(i);
}
System.out.println("sum = " + sum);
}
public static int factor(int n) {
int result = 1;
for (int i = 1; i <= n; i++)