活动地址:CSDN21天学习挑战赛

✨矢志不渝✨

目录
- public static void main(String[] args) {
- //方法的使用
- int a = add(3,8);
- System.out.println(a);
- }
- // 方法的定义
- public static int add(int x, int y) {
- return x + y;
- }
如果方法有返回值,返回值类型必须要与返回的实体类型一致,如果没有返回值,必须写成void
方法名字:采用小驼峰命名
参数列表:如方法没有参数,()中不写,如有参数,需指定参数类型,多个参数之间使用逗号隔开
方法体:方法内部要执行的语句
方法需要写在类中
- public static int getSum(int N){ // N是形参
- return (1+N)*N / 2;
- }
- getSum(10); // 10是实参,在方法调用时,形参N用来保存10
- getSum(100); // 100是实参,在方法调用时,形参N用来保存100
在Java中,实参的值永远都是拷贝到形参中,形参和实参本质是两个实体
示例:
- public class Main{
- public static void swap(int x, int y) {
- int tmp = x;
- x = y;
- y = tmp;
- System.out.println("swap: x = " + x + " y = " + y);
- }
- public static void main(String[] args) {
- int a =10; //局部变量-->栈
- int b =20;
- System.out.println(a+" "+b);
- swap(a,b);
- System.out.println(a+" "+b);
- }
- }

a和b是main方法中的两个变量,其空间在main方法的栈(一块特殊的内存空间)中,而形参x和y是swap方法中的两个变量,x和y的空间在swap方法运行时的栈中,因此:对形参x和y操作不会对实参a和b 产生任何影响。
如果要真正交换这两个变量,必须把这两个变量放堆上,使用引用类型
- public class TestMethod {
- public static void main(String[] args) {
- int[] arr = {10, 20};
- swap(arr);
- System.out.println("arr[0] = " + arr[0] + " arr[1] = " + arr[1]);
- }
- public static void swap(int[] arr) {
- int tmp = arr[0];
- arr[0] = arr[1];
- arr[1] = tmp;
- }
- }
- public class Main{
- public static void main(String[] args) {
- add(1, 2); // 调用add(int, int)
- add(1.5, 2.5); // 调用add(double, double)
- add(1.5, 2.5, 3.5); // 调用add(double, double, double)
- }
- public static int add(int x, int y) {
- return x + y;
- }
-
- public static double add(double x, double y) {
- return x + y;
- }
-
- public static double add(double x, double y, double z) {
- return x + y + z;
- }
- }
注意:
重载和重写有什么区别?
方法名必须相同
参数列表必须不同(参数的个数不同、参数的类型不同、类型的次序必须不同)
与返回值类型是否相同无关
递归的关键有两个:
(1)递归的结束条件(不写会死循环)
(2)递归最后一层和其他有关系的层的关系怎样用非递归函数来表达
比如:斐波纳契数列,当n==1和n==2的时候f(n)=1,这就是递归的终止条件。给了终止条件,计算机才能进行求解子问题并回溯,最终求出f(n)
模拟实现汉诺塔
对于 n 个圆盘的汉诺塔问题,移动圆盘的过程是:
将起始柱上的 n-1 个圆盘移动到辅助柱上;
将起始柱上遗留的 1 个圆盘移动到目标柱上;
将辅助柱上的所有圆盘移动到目标柱上。

- public class Demo{
- public static void main(String[] args) {
- hanio(1,'A','B','C');
- System.out.println();
- hanio(2,'A','B','C');
- System.out.println();
- hanio(3,'A','B','C');
- }
- public static void hanio(int n,char pos1,char pos2,char pos3) {
- if(n == 1) {
- move(pos1,pos3);
- return;
- }
- hanio(n-1,pos1,pos3,pos2);
- move(pos1,pos3);
- hanio(n-1,pos2,pos1,pos3);
- }
- /**
- *
- * @param pos1 起始位置
- * @param pos2 目标位置
- */
- public static void move(char pos1,char pos2) {
- System.out.print (pos1+" -> " + pos2+" ");
- }
- }
-

💖如果文章对你有帮助,请多多点赞、收藏、评论、关注支持!!💖
