1、什么是方法

2、方法的定义使用

1) 代码示例

  1. package com.shen.operator;
  2. public class Demo06 {
  3. public static void main(String[] args) {
  4. System.out.println(test(2,3));
  5. }
  6. public static int test (int num1,int num2){
  7. int num = num1 > num2 ? num1 : num2;
  8. return num;
  9. }
  10. }

2) 定义

image.png

  • 什么是值传递(Java)和引用传递

    • 参考 https://www.zhihu.com/question/31203609

      3、方法的重载

      1) 定义

      image.png

      2) 代码示例

      ```java package com.shen.operator;

      public class Demo06 { public static void main(String[] args) {

      1. double max_value = test(2,3);// 重载 方法名可相同,确保参数类型不同
      2. System.out.println(max_value);

      }

      public static int test (int num1,int num2){

      1. int num = num1 > num2 ? num1 : num2;
      2. return num;

      } public static double test (double num1,double num2,double num3){

      1. double num = num1 > num2 ? num1 : num2;
      2. System.out.println(num3);
      3. return num;

      } }

  1. <a name="mX0sY"></a>
  2. ### 4、命令行传递参数
  3. - 有时候希望在程序运行的时候再给他传递消息,就要靠命令行参数main()函数实现
  4. <a name="pPUwg"></a>
  5. #### 1) 代码示例
  6. ```java
  7. package com;
  8. public class Demo07 {
  9. public static void main(String[] args) {
  10. for (int i = 0; i < args.length;i ++){
  11. System.out.println(i + ": " + args[i]);
  12. }
  13. }
  14. }

2) 调用

  1. javac Demo07.java
  2. java com.shen.operator.Demo07 this is my wife

image.png
image.png

5、可变参数

  1. package com.shen.operator;
  2. public class Demo08 {
  3. public static void main(String[] args) {
  4. printMax(34,3,3,4,5,90,54);
  5. printMax(new double[]{12,2,3,4,5,99,23});
  6. }
  7. public static void printMax(double... numbers){
  8. if(numbers.length == 0){
  9. System.out.println("No args passed");
  10. return;
  11. }
  12. double result = numbers[0];
  13. for(int i = 0;i < numbers.length; i++){
  14. if(numbers[i] > result){
  15. result = numbers[i];
  16. }
  17. }
  18. System.out.println("The max value is " + result);
  19. }
  20. }
  21. ########################################################
  22. The max value is 90.0
  23. The max value is 99.0
  24. 进程已结束,退出代码为 0

6、递归

1) 定义

image.png

2)递归过程图示

image.png

3) 代码示例

  1. package com.shen.operator;
  2. public class Demo09 {
  3. public static void main(String[] args) {
  4. int fn_value = test(3);
  5. System.out.println(fn_value);
  6. }
  7. public static int test(int num){
  8. if (num == 1){
  9. return 1;
  10. }else{
  11. return num * test(num -1 );
  12. }
  13. }
  14. }