Java中方法引數和多引數方法
阿新 • • 發佈:2021-08-11
今天進行了方法引數和多引數方法的學習,覺得和C語言函式中形參和實參類似,記錄一下
2.4 方法引數
先看一下這個程式碼
今天進行了方法引數和多引數方法的學習,覺得和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型別的變數,然後賦不同的值,通過方法引數傳遞過去就能解決了。直接上程式碼:
publicclass 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+"】"); } }