# Java實用但不確定簡不簡單的教學 Day-6 --- ## 函式/方法 在程式語言中,函式(function)是一種可以擁有特定功能的子程式,可以在你的程式中不斷呼叫並執行 而當函式執行完的時候可以回傳新的值 直接看範例可能會比較好懂 ```java public static void main(String[] args) { hello();//在主程式中呼叫了兩次hello hello(); } static void hello(){//定義一個新的函式名字叫做hello //中間的void代表不回傳任何東西 System.out.println("Hello");//印出Hello } ``` 在Java中,我們會把函式稱作方法(method) 所以我們一般會把 ```java public static void main(String[] args) { } ``` 稱作主要方法或是main方法 以下是幾個方法的範例 *方法其實分為類別方法跟實例方法,這裡講的都是類別方法,實例方法之後在物件導向一章會講到,而在類別方法中,前面加上static是必要的 ```java public static void main(String[] args) { int y=5; y=minusTwo(y);//呼叫minusTwo方法 System.out.println(y);//3 String str=hello("Kirito");//呼叫hello方法 System.out.println(str);//Hello Kirito System.out.println(calTriangle(10,20));//100 } static int minusTwo(int x){ //定義一個叫做minusTwo的方法 //中間的int代表此方法會回傳一個int //小括弧中的int x代表他接受一個int參數 return x-2; //return代表回傳 } static String hello(String name){ //接受一個String參數 return "Hello "+name; } static int calTriangle(int base,int height){ //接受兩個int參數 int area=base*height/2; return area;//回傳area,也就是三角形的面積 } ``` 當然也可以在方法中呼叫方法或是自己 ```java static int addOneAndTwo(int num){ return addOne(num)+addTwo(num); } static int addOne(int num){ return num+1; } static int addTwo(int num){ return num+2; } static int addOneUntilFive(int num){//可以猜猜看他是怎麼執行的 if(num>=5){ return num; } return addOneUntilFive(num+1); } ``` --- ## 參數ㄉ傳值或傳址 當你在使用方法並傳入不同型態參數ㄉ同時,你會發現有些很奇特的現象 像是 ```java public static void main(String[] args) { int x = 0; addOne(x);//1 System.out.println(x);//0 } static void addOne(int m){ m++; System.out.println(m); } ``` 或是 ```java public static void main(String[] args) { int[] x = {5,2}; addOne(x);//6 System.out.println(x[0]);//6 } static void addOne(int[] m){ m[0]++; System.out.println(m[0]); } ``` 到底為什麼結果會ㄅ一樣呢? 這時候就要說到 * 傳值呼叫(Call By Value) * 傳參考呼叫(Call By Reference) 我們知道,程式裡的變數其實都是存在記憶體裡面的,而要存取這些變數的值便是透過存取存放這些變數的「位址」 而當我們將參數傳入方法的時候,其實會根據資料型態的不同來決定我們是用哪種方式 方式|說明 ------|----- Call By Value | 將變數的值存進新的記憶體位址,所以不會動到原本的變數 Call By Reference | 直接存取原本記憶體的位置,所以當傳進去的參數變動時,原本的變數也會變 資料型態|方式 ----------|---- 基本資料型態(int、char、double)|Call By Value String字串| Call By Value (雖然他其實在Java裡是物件) 陣列|Call By Reference Java物件 | Call By Reference 其實在C裡面還有一種叫做傳址呼叫,是把變數的位址傳進新的記憶體位址的值,不過Java並沒有這種東西,所以不過多著墨 可以參考[五分鐘快速了解 [傳址,傳參考,傳址]](https://ithelp.ithome.com.tw/articles/10198215) --- ## 練習題目 其實並沒有什麼OnlineJudge的題目可以寫 不過可以嘗試看看用函式完成下列的題目 * 攝氏與華氏溫標轉換(公式:$F=(9*C)/5+32$) * 輸出圓形面積
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up