什么是方法?

什么是方法?介绍:

  • java的方法类似于其他语言的函数

  • 方法是语句的集合,他们在一起执行一个功能

  • 方法是解决一类问题的步骤的有序组合

  • 方法包含于类或者对象中

  • 方法在程序中被创建,在其他地方被引用

     

    结构:

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

    。。。

    方法体

    。。。

    return 返回值;

    }

     

    //调用方法:加法和水仙花数

    package com.company;

    /**
    *
    * @Desciption
    * @author Abraham
    * @email 1290807550@qq.com
    * @version JDK1.8
    * @date 2021年3月16日上午9:01:04
    */


    public class method01 {
     
  • public static void main(String[] args) {
  •        //int add=add(1,2);
  •         //System.out.println(add);
      flower();


      }
      //加法:
      public static int add(int a,int b) {
      return a+b;
      }
      //输出水仙花数:
      public static void flower() {
          for (int i = 100; i < 1000; i++) {
              int h = i / 100;
              int t = (i / 10) % 10;
              int o = i % 10;
              if (h * h * h + t * t * t + o * o * o == i) {
                  System.out.println(i + "=" + h + "*" + h + "*" + h + "+" + t + "*" + t + "*" + t + "+" + o + "*" + o + "*" + o);
              }
          }
      }}

    再来两个案例(比大小):

    package com.company;

    /**
    *
    * @Desciption
    * @author Abraham
    * @email 1290807550@qq.com
    * @version JDK1.8
    * @date 2021年3月16日上午9:01:04
    */


    public class method02 {
  •     public static void main(String[] args){
          //做一个比大小的方法
      int result=max(10,20);
          System.out.println(result);

      }
      public static int max(int num1,int num2) {
        int result=0;

          if(num1>num2){
            result=num1; }
          else{result=num2;}
          if(num1==num2){
              System.out.println("num1==num2");
              return 0; }
            return result;

      }

    }
    /*
    输出结果:20
    */

    输出20以内不被4整除的正整数:

    package com.company;

    /**
    *
    * @Desciption
    * @author Abraham
    * @email 1290807550@qq.com
    * @version JDK1.8
    * @date 2021年3月16日上午9:01:04
    */


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

        num();
      }
      public static void num(){
          int a = 20;
          for (int i=1;i<a;++i){
              if(i%4==0){
                  continue; }
              System.out.print(i+"\t");
          }
      }
    }

     //输出结果:1 2 3 5 6 7 9 10 11 13 14 15 17 18 19

设计方法的原则:

方法的本意就是功能块,就是实现某个功能的语句块的集合。我们设计方法的时候,最好保持方法的原子性,就是一个方法只完成一个功能,这样有利于我们后期的拓展。

 

方法命名规则:首字母小写,驼峰命名法。

 

posted @ 2021-03-14 00:02  gAbraham  阅读(231)  评论(0)    收藏  举报