1. 程式人生 > 實用技巧 >帶返回值方法的定義格式

帶返回值方法的定義格式

 1 package day05;
 2 
 3 public class MethodDemo04 {
 4     public static void main(String[] args) {
 5         /*帶返回值方法的定義格式:
 6          * public static 資料型別 方法名(引數){
 7          *   return 資料;
 8          * }
 9          * 方法定義時return後面的返回值與方法定義上的資料型別要匹配,否則程式將報錯
10          * 帶返回值方法的呼叫格式:
11          * 資料型別 變數名 = 方法名(引數)
12 * */ 13 int num = add(10, 20); 14 System.out.println(num); 15 } 16 17 public static int add(int a, int b) { 18 int c = a + b; 19 return c; 20 } 21 }

執行結果:

eg:

 1 package day05;
 2 
 3 public class MethodDemo05 {
 4     public static void main(String[] args) {
5 System.out.println(getMax(1, 9)); 6 int result = getMax(1, 9); 7 for (int i = 1; i <= result; i++) { 8 System.out.println("hello"); 9 } 10 } 11 12 //方法可以獲取兩個數的最大值 13 public static int getMax(int a, int b) { 14 if (a > b) { 15
return a; 16 } else { 17 return b; 18 } 19 } 20 }

執行結果: