方法
方法的定义类似 c++中的函数,格式为
1 2 3 4 5
| 修饰符 返回值类型 方法名(参数1.参数2,...){ 方法体 return 返回值; } 在函数的调用处参数为实参,形参和实参要一一对应。
|
这里写一个求阶乘的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import java.util.Scanner;
public class Main{ public static int fact(int n){ int res=1; for(int i=2;i<=n;i++) { res*=i; } return res; } public static void main(String[] args) { int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); System.out.printf("%d",fact(n)); } }
|
参数传递
- 将实参的初始值拷贝给形参。此时,对形参的改动不会影响实参的初始值。
- 将实参的引用(地址)传给形参,通过引用找到变量的真正地址,然后对地址中的值修改。所以此时对形参的修改会影响实参的初始值。
方法重载
方法重载是指:在同一个类中存在多个方法,方法名称相同但参数列表不同。
编译器会根据实参的类型选择最匹配的方法来执行。
比如对取最值函数进行重载:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.util.Scanner; public class Main{ public static int max(int a,int b) { System.out.println("INT最大值:"); if(a>b)return a; else return b; } public static double max(double a,double b) { System.out.println("DOUBLE最大值:"); if(a>b)return a; else return b; } public static void main(String[] args) { System.out.println(max(3,4)); System.out.println(max(8.8888,6.5454)); } }
|
输出
1 2 3 4
| INT最大值: 4 DOUBLE最大值: 8.8888
|
方法递归调用
比如在方法内部去调用这个方法。
比如递归求斐波那契数列:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import java.util.Scanner; public class Main{ public static int fib(int n) { if(n<=2)return 1; return fib(n-1)+fib(n-2); } public static void main(String[] args) { int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); System.out.println(fib(n)); } }
|