今天進行了方法參數和多參數方法的學習,覺得和C語言函數中形參和實參類似,記錄一下
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); } }

實際上方法參數和聲明變量並無區別,只是這個變量是要定義在方法參數這個位置里,編程語言里把這個聲明的變量叫做形參
方法調用
如果有了參數聲明后,就必須要傳入參數, 這個參數可以是變量也可以是值,只是要注意數據類型要匹配,編程語言把這個傳遞的變量稱為實參
// 直接傳值 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+"】"); } }
注意多個形參之間用逗號隔開。
附加:繼續死磕一下隨機數的產生,運行幾遍后會發現,其實第一位並不隨機,因為我們的第一位永遠是1,那么就需要讓Math.random的結果*9+1來實現
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+"】"); } }
