方法

方法

修饰符 返回值类型 方法名(参数类型 参数名){ 。。。

方法体

。。。

return 返回值;

}

形参 实参

package com.method;

public class Domn01 {
  //main 方法
  public static void main(String[] args) {

      //实际参数:实际调用传递给他的参数
      int sum=add(1,2);
      System.out.println(sum);

      test();

  }

  //加法
  //形式参数,用来定义作用的
  public static int add(int a,int b){
      return a+b;
  }

  public static void test(){
      for (int j = 1; j <= 9; j++) {
          for (int i = 1; i <= j; i++) {
              System.out.print(j+"*"+i+"="+(j*i)+ "\t");
          }
          System.out.println();
      }
  }
}

java为值传递

还有引用传递

方法的重载

方法可以重名,但是参数列表必须不同(个数、类型、参数排列顺序不同等)

 

package com.method;

public class Domn02 {
  public static void main(String[] args) {
      int man=man(10,10);
      System.out.println(man);

  }

  //比大小
  public static int man(int a,int b){
      int result =0;
      if (a>=b){
          result=a;
      }else{
          result=b;
      }
      return result;
  }
  public static double man(double a,double b){
      double result =0;
      if (a>=b){
          result=a;
      }else{
          result=b;
      }
      return result;
  }
}

重载中可以设置可变参数

可变参数只能放在最后面

package com.method;

public class Domn04 {
  public static void main(String[] args) {
      Domn04 domn04=new Domn04();
      domn04.test(1,2,3,4,5,6);
      printMax(34,6,4,64,3.2);
      printMax(new double[]{1,2,3});

  }
  public static void printMax(double... number){
      if (number.length==0){
          System.out.println("No argument passed");
          return;
      }
      double result=number[0];

      for (int i = 1; i <number.length ; i++) {
          if (number[i]>result){
              result=number[i];
          }
      }
      System.out.println("The man value is "+result);

  }



  public void test(int... i){
      System.out.println(i[2]);
  }
}
posted @ 2020-04-12 11:19  乖执事  阅读(155)  评论(0)    收藏  举报