天天看點

Java中方法參數和多參數方法

Java中方法參數和多參數方法

今天進行了方法參數和多參數方法的學習,覺得和C語言函數中形參和實參類似,記錄一下

2.4 方法參數

先看一下這個代碼

2.4 方法參數

1 public class Custom {
 2 
 3   public static void main(String[] args) {
 4     random();
 5     code();
 6   }
 7 
 8   /**
 9   *生成6位随機數
10   */
11   public static void random(){
12     int code = (int) ((Math.random()+1) * 100000);
13     System.out.println(code);
14   }
15 
16   /**
17   *生成4位随機數
18   */
19   public static void code(){
20     int code = (int) ((Math.random()+1) * 1000);
21     System.out.println(code);
22   }
23 
24 }      

觀察可以發現,random和code代碼其實沒有太大的差別,隻有*100000和*1000這個行為的差別。

為了解決這個問題,引入一個概念,那就是方法參數,我們可以把100000和1000這個數字定義為一個int類型的變量,然後賦不同的值,通過方法參數傳遞過去就能解決了。直接上代碼:

public class Custom {

  public static void main(String[] args) {
    random(100000);
    random(1000);
  }

  /**
  *生成随機數
  */
  public static void random(int length){
    int code = (int) ((Math.random()+1) * length);
    System.out.println(code);
  }

}      
Java中方法參數和多參數方法

 實際上方法參數和聲明變量并無差別,隻是這個變量是要定義在方法參數這個位置裡,程式設計語言裡把這個聲明的變量叫做形參

方法調用

如果有了參數聲明後,就必須要傳入參數, 這個參數可以是變量也可以是值,隻是要注意資料類型要比對,程式設計語言把這個傳遞的變量稱為實參

// 直接傳值
random(100000);

// 傳遞變量
int len = 100000;
random(len);      

2.5 多參數方法

先來看一串代碼

public class MessageCode {

  public static void main(String[] args) {
    code(1000);
  }

  public static void code(int len){
      int code = (int)((Math.random()+1)*len);
      System.out.println("親愛的使用者,你本次的驗證碼是【"+code+"】");
  }

}      

在實際工作當中,文案部分經常會被調整,如果每次都要修改方法内容,那麼就會導緻複用以及維護成本變高,是以我們會把文案也定義成變量。

在這個場景下,我們就需要定義多個參數了,看一下下邊的這段代碼

public class MessageCode {

  public static void main(String[] args) {
    String text = "親愛的使用者,你本次的驗證碼是";
    code(text,1000);
  }

  public static void code(String text,int len){
      int code = (int)((Math.random()+1)*len);
      System.out.println(text+"【"+code+"】");
  }

}      
public class MessageCode {

  public static void main(String[] args) {
    String text = "親愛的使用者,你本次的驗證碼是";
    code(text,1000);
  }

  public static void code(String text,int len){
      int code = (int)(((Math.random()*9)+1)*len);
      System.out.println(text+"【"+code+"】");
  }

}      

繼續閱讀