# JAVA Method ###### tags: `Java` --- 以下內文Method又稱函式(function)也稱方法 Java函式的特點整理如下: (1)Java的函式隸屬於某一個類別,函式擁有屬於自己的名稱,除非透過多載(overload)技術,否則不允許宣告兩個相同名稱的函式。 (2)函式內宣告的變數為『區域變數』,換句話說,在不同函式內可以使用相同的變數名稱,因為該變數只會在該函式中生效。 >練習:建立由n 加到m 總和total = n+(n+1)+(n+2)+…+m 並可回傳結果值的方法,使用return 敘述呼叫方法分別求1 到10 及5 到12 的總和傳回。 ```java= public class Ex09_05_total { public static void main(String[] args) { int tot1, tot2; tot1= sum(1,10); //把()內的兩個值傳給sum計算 System.out.println("1加到10=" +tot1+ "\n"); tot2= sum(5,12); System.out.println("5加到12=" +tot2+ "\n"); } static int sum(int S, int E ){ int total = 0; for(int a = S; a <= E; a++){ //a=s=1,1<=10,1執行++到10 total += a; //總和等於總和本身+a的值 } return total; //把值回傳給sum,沒有回傳就無法成立tot1跟tot2值的代入 } } ``` ## 提取陣列 ```java= package Ex09; public class Ex09_08_Method_Arrays { public static void main(String[] args) { int[] myArray = new int[] {31, 12, 16, 10, 78}; //設定陣列的值 System.out.println("【排序前】"); for (int i = 0; i < myArray.length; i++) { System.out.println(" " + myArray[i]); //設定如果i<myArray的陣列數就要++ } bubbleSort(myArray); System.out.println(); System.out.println("【排序後】"); for (int i = 0; i < myArray.length; i++) { System.out.println(" " + myArray[i]); } } static void bubbleSort(int[] vArray) { //設定一個Method叫做bubbleSort,他的值為陣列vArray int tmp = 0; for (int i = vArray.length - 2; i >= 0; i--) { // for (int j = 0; j <= i; j++) { if (vArray[j] > vArray[j + 1]) { tmp = vArray[j]; vArray[j] = vArray[j+1]; vArray[j + 1] = tmp; } } } }//psvm end }// class Ex09_08_Method_Arrays end ``` --- <span class="code1"></span> <style> h2 { color: #2383B8; } h3 { color: #1AA340; } h4 { color: white; background-color: #2383B8; padding:8px; } .code1 { padding: 2px 4px; font-size: 90%; color: #c7254e; background-color: #f9f2f4; border-radius: 4px; font-family:'Fira Code'; } .code { padding: 2px 4px; font-size: 90%; font-family:'Fira Code'; } </style>
×
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